Leetcode Add Digits
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.
java code(3 methods)
1 public class AddDigits { 2 public static void main(String[] args) { 3 //int x = 2048; 4 System.out.println("in out"); 5 for (int i = 0; i<= 29; i++) { 6 int result = addDigits(i); 7 System.out.printf("%2d %2d", i, result); 8 System.out.println(); 9 } 10 } 11 12 /* 13 * method 1 14 * run time: 344ms slow 15 * */ 16 public static int addDigits(int num) { 17 int sum = 0; 18 if( num < 10) { 19 return num; 20 } 21 while(num >=10) { 22 sum += num%10; 23 num /= 10; 24 } 25 sum += num; 26 return addDigits(sum); 27 } 28 29 /* 30 * method 2 31 * run time: 276ms medium 32 * */ 33 public static int addDigits(int num) { 34 while (num / 10 > 0) { 35 int sum = 0; 36 while (num > 0) { 37 sum += num % 10; 38 num /= 10; 39 } 40 num = sum; 41 } 42 return num; 43 } 44 45 /* 46 * method 3 47 * run time: 240ms fast!! 48 * */ 49 public static int addDigits(int num) { 50 return (num -1) % 9 +1; 51 }
Reference:
1. http://bookshadow.com/weblog/2015/08/16/leetcode-add-digits/
2. http://www.cnblogs.com/grandyang/p/4741028.html