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);
}
相关推荐
Swift社区7 小时前
LeetCode 465 最优账单平衡
算法·leetcode·职场和发展
聆风吟º7 小时前
【数据结构手札】空间复杂度详解:概念 | 习题
java·数据结构·算法
weixin_445054728 小时前
力扣热题51
c++·python·算法·leetcode
地平线开发者8 小时前
linux 常见稳定性问题分析方法
算法·自动驾驶
s砚山s8 小时前
代码随想录刷题——二叉树篇(九)
算法
地平线开发者8 小时前
大模型常见量化方法简介
算法·自动驾驶
smj2302_7968265211 小时前
解决leetcode第3801题合并有序列表的最小成本
数据结构·python·算法·leetcode
栗少11 小时前
英语自学手册:系统化进阶指南基于《英语自学手册》的方法论与行动路径
人工智能·算法
Xの哲學12 小时前
深入解析 Linux systemd: 现代初始化系统的设计与实现
linux·服务器·网络·算法·边缘计算
sinat_2554878112 小时前
InputStream/OutputStream小讲堂
java·数据结构·算法