Question
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
Example
Given num = 38.
The process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return 2.
Challenge
Could you do it without any loop/recursion in O(1) runtime?
Thinking
General solution:
Using mod(%) get first digit
Using divid(/) get other digits until digit is less than 10
Challenge solution:
It is a Digital root question. The formula is:
dr(n) = 1 + ((n-1) % 9)
Solution
Java (Challenge solution)
public class Solution {
/**
* @param num a non-negative integer
* @return one digit
*/
public int addDigits(int num) {
// Write your code here
if (num < 10) {
return num;
}
return (num - 1) % 9 + 1;
}
}
Java (Normal solution)
public class Solution {
/**
* @param num a non-negative integer
* @return one digit
*/
public int addDigits(int num) {
// Write your code here
if (num < 10) {
return num;
}
while (num >= 10) {
int tmp = 0;
while (num >= 10) {
tmp = tmp + num % 10;
num = num /10;
}
num = num + tmp;
}
return num;
}
}