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?
---------------------------------------------------SOLUTION BELOW---------------------------------------------------
The idea is simple. Write a loop to record the length of the number, which means how many digits. And another loop for counting the sum of current number. It shocked me because it took me more than 10 minutes to write about it!!! I have been away from Leetcode really long time. I really should spend more time on algorithms and data structure. Besides, I will also start to write what I learnt in J2EE in the past year and keep updating in this blog. My current project in UfT is also attractive and I would move it here if possible. It's a shame here is not a SVN, pity.
First Solution:
package testAndfun;
public class addDigit {
public static void main(String args[]){
int num = 12;
addDigit ad = new addDigit();
// System.out.println(cal(209874));
System.out.println(ad.addDigits(num));
}
public int addDigits(int num) {
while((num+"").length()!=1){
int tmp = 0;
while(num!=0){
tmp += num % 10;
num = num / 10;
// System.out.println(num);
}
num = tmp;
}
return num;
}
}
However, if you could observe the pattern of the answer. Let me show you:
-------------------------------------
| when input is 0 the answer is 0 |
| when input is 1 the answer is 1 |
| when input is 2 the answer is 2 |
| when input is 3 the answer is 3 |
| when input is 4 the answer is 4 |
| when input is 5 the answer is 5 |
| when input is 6 the answer is 6 |
| when input is 7 the answer is 7 |
| when input is 8 the answer is 8 |
| when input is 9 the answer is 9 |
| when input is 10 the answer is 1 |
| when input is 11 the answer is 2 |
| when input is 12 the answer is 3 |
| when input is 13 the answer is 4 |
| when input is 14 the answer is 5 |
| when input is 15 the answer is 6 |
| when input is 16 the answer is 7 |
| when input is 17 the answer is 8 |
| when input is 18 the answer is 9 |
| when input is 19 the answer is 1 |
| when input is 20 the answer is 2 |
-------------------------------------
Do you see? The pattern is bloody easy. I will just write it down. This time, Python.class Solution:
def addDigits(self, num):
if num == 0:
return 0
return (num - 1) % 9 + 1