码迷,mamicode.com
首页 > 其他好文 > 详细

258 Add Digits

时间:2015-09-08 06:58:45      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

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 = 111 + 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:

  1. A naive implementation of the above process is trivial. Could you come up with other methods?
  2. What are all the possible results?
  3. 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

 

258 Add Digits

标签:

原文地址:http://www.cnblogs.com/anne-vista/p/4790486.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!