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);
}
相关推荐
一个不知名程序员www12 分钟前
算法学习入门---二分查找(C++)
c++·算法
2301_8079973837 分钟前
代码随想录-day26
数据结构·c++·算法·leetcode
闭着眼睛学算法1 小时前
【双机位A卷】华为OD笔试之【排序】双机位A-银行插队【Py/Java/C++/C/JS/Go六种语言】【欧弟算法】全网注释最详细分类最全的华子OD真题题解
java·c语言·javascript·c++·python·算法·华为od
TL滕1 小时前
从0开始学算法——第一天(认识算法)
数据结构·笔记·学习·算法
小欣加油1 小时前
leetcode 3318 计算子数组的x-sum I
c++·算法·leetcode·职场和发展
love is sour1 小时前
聚类(Clustering)详解:让机器自己发现数据结构
算法·支持向量机·聚类
烟袅1 小时前
LeetCode 142:环形链表 II —— 快慢指针定位环的起点(JavaScript)
前端·javascript·算法
CoovallyAIHub1 小时前
OCR战场再起风云:LightOnOCR-1B凭什么比DeepSeekOCR快1.7倍?(附演示开源地址)
深度学习·算法·计算机视觉
海琴烟Sunshine2 小时前
leetcode 190. 颠倒二进制位 python
python·算法·leetcode
Xの哲學2 小时前
Linux eMMC子系统深度解析:从硬件协议到内核实现
linux·网络·算法·架构·边缘计算