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);
}
相关推荐
pcm1235671 分钟前
设计C/S架构的IM通信软件(4)
java·c语言·架构
徐小夕@趣谈前端6 分钟前
Web文档的“Office时刻“:jitword共建版2.0发布!让浏览器变成本地生产力
前端·数据结构·vue.js·算法·开源·编辑器·es6
问好眼9 分钟前
【信息学奥赛一本通】1275:【例9.19】乘积最大
c++·算法·动态规划·信息学奥赛
Daydream.V28 分钟前
逻辑回归实例问题解决(LogisticRegression)
算法·机器学习·逻辑回归
代码无bug抓狂人28 分钟前
C语言之表达式括号匹配
c语言·开发语言·算法
不穿格子的程序员36 分钟前
从零开始写算法——普通数组篇:缺失的第一个正数
算法·leetcode·哈希算法
Nebula_g42 分钟前
线程进阶: 无人机自动防空平台开发教程(更新)
java·开发语言·数据结构·学习·算法·无人机
rit84324991 小时前
基于MATLAB的环境障碍模型构建与蚁群算法路径规划实现
开发语言·算法·matlab
hoiii1871 小时前
MATLAB SGM(半全局匹配)算法实现
前端·算法·matlab
独自破碎E1 小时前
大整数哈希
算法·哈希算法