题目
给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。返回这个结果。
示例 1:
输入: num = 38
输出: 2
解释: 各位相加的过程为:
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
由于 2 是一位数,所以返回 2。
示例 1:
输入: num = 0
输出: 0
代码
public class E258 {
public static int addDigits(int num) {
while (num >= 10) {
num = num / 10 + num % 10;
}
return num;
}
public static void main(String[] args) {
System.out.println(addDigits(38));
}
}
时间复杂度为 o(1) 的 大佬写法:
public static int addDigits(int num) {
return (num - 1) % 9 + 1;
}
假如一个三位数’abc’,其值大小为s1 = 100 * a + 10 * b + 1 * c,经过一次各位相加后,变为s2 = a + b + c,减小的差值为(s1 -s2) = 99 * a + 9 * b,差值可以被9整除,每一个循环都这样,缩小了9的倍数。
附:测试图
来源
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-to-array-form-of-integer