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);
}
相关推荐
Frostnova丶几秒前
(11)LeetCode 239. 滑动窗口最大值
数据结构·算法·leetcode
爱编码的小八嘎8 分钟前
C语言完美演绎6-9
c语言
GoCoding11 分钟前
YOLO-Master 与 YOLO26 开始
算法
VALENIAN瓦伦尼安教学设备14 分钟前
设备对中不良的危害
数据库·嵌入式硬件·算法
weixin_6495556719 分钟前
C语言程序设计第四版(何钦铭、颜晖)第十一章指针进阶之奇数值结点链表
c语言·开发语言·链表
参.商.34 分钟前
【Day48】46. 全排列
leetcode·golang
不熬夜的熬润之37 分钟前
APCE-平均峰值相关能量
人工智能·算法·计算机视觉
yzx99101338 分钟前
实时数据流处理实战:从滑动窗口算法到Docker部署
算法·docker·容器
呜喵王阿尔萨斯1 小时前
argc & argv
c语言·c++
爱编码的小八嘎1 小时前
C语言完美演绎6-1
c语言