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?
This is a pure math problem.
The O(1) solution is based on the mathematical property of congruence.
The Digital Root of a number is same as the remainder when that number is divided by 9 (and this remainder will always be a single digit)
Application of Digit Root:
Digital roots can be used as a sort of checksum, to check that a sum has been performed correctly.
If it has, then the digital root of the sum of the given numbers will equal the digital root of the sum of the digital roots of the given numbers.
This check, which involves only single-digit calculations, can catch many errors in calculation.
Recursion:
class Solution {
public int addDigits(int num) {
if(num<10) return num;
int sum=0;
while(num!=0){
sum+=num%10;
num/=10;
}
return addDigits(sum);
}
}
1-Line:
public class Solution {
public int addDigits(int num) {
return num==0?0:(num%9==0?9:(num%9));
}
}