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);
}
相关推荐
sjsjs1117 分钟前
【数据结构-扫描线】力扣57. 插入区间
数据结构·算法·leetcode
王哈哈嘻嘻噜噜19 分钟前
数据结构中线性表的定义和特点
数据结构·算法
一杯茶一道题38 分钟前
LeetCode 260. 只出现一次的数字 III
算法·leetcode
MogulNemenis39 分钟前
力扣415周赛
java·数据结构·算法·leetcode
Rense143 分钟前
常用的基于无线射频( UWB)室内定位技术的原理与算法
算法
zzhnwpu44 分钟前
代码随想录算法训练营第三七天| 动态规划:完全背包理论基础 518.零钱兑换II 377. 组合总和 Ⅳ 322. 零钱兑换
算法·leetcode·动态规划
奇点 ♡1 小时前
【线程】线程的控制
linux·运维·c语言·开发语言·c++·visual studio code
一道秘制的小菜1 小时前
C++第十一节课 new和delete
开发语言·数据结构·c++·学习·算法
学不会lostfound1 小时前
一、机器学习算法与实践_03概率论与贝叶斯算法笔记
算法·机器学习·概率论·高斯贝叶斯
学地理的小胖砸1 小时前
【高分系列卫星简介——高分一号(GF-1)】
开发语言·数码相机·算法·遥感·地理信息