LeetCode //C - 258. Add Digits

258. Add Digits

Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.

Example 1:

Input: num = 38
Output: 2
Explanation: The process is

38 --> 3 + 8 --> 11

11 --> 1 + 1 --> 2

Since 2 has only one digit, return it.

Example 2:

Input: num = 0
Output: 0

Constraints:
  • 0 < = n u m < = 2 31 − 1 0 <= num <= 2^{31} - 1 0<=num<=231−1

From: LeetCode

Link: 258. Add Digits


Solution:

Ideas:

1. Digital Root Concept: The digital root of a number is the single-digit value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration. The digital root can be directly calculated using the formula:

  • If num == 0, then the digital root is 0.
  • If num % 9 == 0, then the digital root is 9 (except when num is 0).
  • Otherwise, the digital root is num % 9.

2. Mathematical Insight:

  • The digital root of a non-zero number is 1 + (num - 1) % 9, which simplifies to the above formula in the code.

3. Code Explanation:

  • If num is 0, return 0.
  • Otherwise, check if num % 9 == 0. If true, return 9 because the number is divisible by 9 and non-zero.
  • If num % 9 != 0, return num % 9.
Code:
c 复制代码
int addDigits(int num) {
    if (num == 0) return 0;
    return (num % 9 == 0) ? 9 : (num % 9);
}
相关推荐
Magnum Lehar10 分钟前
vulkan游戏引擎test_manager实现
java·算法·游戏引擎
水蓝烟雨42 分钟前
[面试精选] 0094. 二叉树的中序遍历
算法·面试精选
超闻逸事1 小时前
【题解】[UTPC2024] C.Card Deck
c++·算法
暴力求解1 小时前
C++类和对象(上)
开发语言·c++·算法
JKHaaa1 小时前
几种简单的排序算法(C语言)
c语言·算法·排序算法
让我们一起加油好吗1 小时前
【基础算法】枚举(普通枚举、二进制枚举)
开发语言·c++·算法·二进制·枚举·位运算
FogLetter2 小时前
微信红包算法揭秘:从随机性到产品思维的完美结合
算法
BUG收容所所长2 小时前
二分查找的「左右为难」:如何优雅地找到数组中元素的首尾位置
前端·javascript·算法
itsuifengerxing3 小时前
python 自定义无符号右移
算法
猎板PCB厚铜专家大族3 小时前
高频 PCB 技术发展趋势与应用解析
人工智能·算法·设计规范