Add Digits 解答
Question
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?
Hint:
- A naive implementation of the above process is trivial. Could you come up with other methods?
- What are all the possible results?
- How do they occur, periodically or randomly?
- You may find this Wikipedia article useful.
Solution
Naive way is to use two loops.
1 public class Solution { 2 public int addDigits(int num) { 3 int copy = num; 4 while (copy / 10 > 0) { 5 int newNum = 0; 6 while (copy / 10 > 0) { 7 newNum += copy % 10; 8 copy /= 10; 9 } 10 newNum += copy; 11 copy = newNum; 12 } 13 return copy; 14 } 15 }
There is a math relationship.
1 public class Solution { 2 public int addDigits(int num) { 3 if (num == 0) 4 return num; 5 if (num % 9 == 0) 6 return 9; 7 return (num % 9); 8 } 9 }