LeetCode //C - 258. Add Digits
创始人
2024-12-14 03:35:24

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:
int addDigits(int num) {     if (num == 0) return 0;     return (num % 9 == 0) ? 9 : (num % 9); }  

相关内容

热门资讯

长光卫星8颗卫星今日出征 将于... 5月17日,长光卫星技术股份有限公司在吉林省航天信息产业园举行“文物01星”、“彩云光学01星”、“...
管网式七氟丙烷气体灭火装置厂家... 导语:管网式七氟丙烷气体灭火装置作为高效环保的消防设备,广泛应用于工业厂房、电力设施、档案馆等场景。...
让好故事更好抵达观众(人文茶座... 牛梦笛 打开手机,嫦娥奔月的故事在AI(人工智能)影像里重现;节气传说、上古神话,在小小屏幕间次第展...
蜂巢能源申请电池模组和电池包专... 国家知识产权局信息显示,蜂巢能源科技股份有限公司申请一项名为“电池模组和电池包”的专利,公开号CN1...
乐道做对了,也稳住了 “两年前,乐道品牌第一次和大家见面。那时候有人问:中国市场还需要一个新品牌吗?纯电品牌真的能活下来吗...