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);
}
相关推荐
hetao17338378 分钟前
2026-10-03 hetao1733837 的刷题记录
c++·算法
小灰灰搞电子17 分钟前
C语言 <stdio.h> 头文件详解
c语言·stdio.h
这张生成的图像能检测吗21 分钟前
(论文速读)Object-Driven Multi-Layer Scene Decomposition:从单张图像恢复遮挡后的多层场景
人工智能·算法·计算机视觉·rgb-d·场景分解
嘎嘎风23 分钟前
MiniMind 学习笔记之 01 一个 64M 的模型,凭什么像 ChatGPT?
算法
Evand J30 分钟前
【MATLAB例程】三维快速扩展随机树(RRT)路径规划与到达角(AOA)定位算法|三维避障+定位仿真。附下载链接
开发语言·算法·matlab·路径规划·定位
漂流瓶jz1 小时前
UVA-1610 聚会游戏 题解答案代码 算法竞赛入门经典第二版
数据结构·c++·算法·题解·aoapc·算法竞赛入门经典·uva
yyy(十一月限定版)1 小时前
CF2131D Arboris Contractio
算法
朝朝辞暮i1 小时前
C++ 第 28 课:Lambda 表达式
开发语言·c++·算法
代码什么用1 小时前
LeetCode-560.和为 K 的子数组
算法·leetcode
All for pursuit.1 小时前
【回溯-3】39.组合总和
数据结构·c++·算法·leetcode