版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014539580/article/details/78046842
Given a non-negative integer num
, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38
, the process is like: 3 + 8 = 11
, 1 + 1 = 2
. Since 2
has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
//正常方法
class Solution {
public int addDigits(int num) {
// return num - 9 *((num - 1) / 9);
// return num == 0? 0 : (num % 9 == 0 ? 9 : num % 9);
while(num >= 10){
int temp = num;
int sum = 0;
while(temp != 0){
sum += temp % 10;
temp = temp / 10;
}
num = sum;
}
return num;
}
}
//找规律 ,惊呆了
class Solution {
public int addDigits(int num) {
return 1 + (num - 1) % 9;
}
}