LeetCode Add Digits

原题链接在这里:https://leetcode.com/problems/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 = 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?

题解:

最基本的想法就是每一位相加知道成为个位数,但本题有follow-up, require O(1) time.

最后的结果只能是0-9. 列数看结果,发现num%9对于大多数正数得到了最后结果。

但corner case 9和9的倍数,本应该返回9, 却返回了0, 所以单独讨论。

Method 3 是返回(num-1)%9+1,  避免了9与9的倍数corner case, 但需要注意新的corner case num == 0. num - 1 就成了负数,此时num==0需要单独讨论。

Time Complexity: Method 3, O(1). Space: O(1).

AC Java:

 1 public class Solution {
 2     public int addDigits(int num) {
 3         /*
 4         //Method 1
 5         while(num/10 != 0){
 6             int sum = 0;
 7             while(num>0){
 8                 sum += num%10;
 9                 num = num/10;
10             }
11             num = sum;
12         }
13         return num;
14         
15         //Method 2
16         if(num == 0){
17             return 0;
18         }
19         if(num%9 == 0){
20             return 9;
21         }
22         return num%9;
23         */
24         
25         //Method 3
26         if(num == 0){
27             return 0;
28         }
29         return (num-1)%9+1;
30     }
31 }

 

posted @ 2015-08-17 01:13  Dylan_Java_NYC  阅读(163)  评论(0编辑  收藏  举报