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);
}
相关推荐
CoovallyAIHub2 分钟前
避开算力坑!无人机桥梁检测场景下YOLO模型选型指南
深度学习·算法·计算机视觉
橙小花5 分钟前
C语言:指针、变量指针与指针变量、数组指针与指针数组
c语言·开发语言
YouQian7726 分钟前
问题 C: 字符串匹配
c语言·数据结构·算法
yanxing.D11 分钟前
408——数据结构(第二章 线性表)
数据结构·算法
SoveTingღ32 分钟前
【开发环境配置】VScode里面配置cmake遇到的问题
c语言·vscode·cmake·嵌入式软件·开发环境配置
艾莉丝努力练剑41 分钟前
【LeetCode&数据结构】二叉树的应用(二)——二叉树的前序遍历问题、二叉树的中序遍历问题、二叉树的后序遍历问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
YuTaoShao1 小时前
【LeetCode 热题 100】51. N 皇后——回溯
java·算法·leetcode·职场和发展
1 小时前
3D碰撞检测系统 基于SAT算法+Burst优化(Unity)
算法·3d·unity·c#·游戏引擎·sat
Tony沈哲1 小时前
OpenCV 图像调色优化实录:基于图像金字塔的 RAW / HEIC 文件加载与调色实践
opencv·算法
我就是全世界2 小时前
Faiss中L2欧式距离与余弦相似度:究竟该如何选择?
算法·faiss