Leetcode:Add digits

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?



Answer

In.  Out.
1    1
2.   2
3.   3
4.   4
5.   5
6.   6
7.   7
8.   8
9.   9
10.   1
11.   2
12.   3
13.   4
14.   5
15.   6
16.   7
17.   8
18.   9
19.   1
20.   2
21.   3
22.   4
23.   5
24.   6
25.   7

從輸入輸出可以看出是以9作為一個循環,因此我們只要對整個數字取除9的餘數就能知道輸出結果。

Javascript

_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
var addDigits = function(num) {
   
    if(num <= 9){
        return num;
    }else{
        var x = num % 9;
        if (x === 0){
            return 9;
        }else{
            return x;
        }
    }
}
_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/

光看這冗長的code實在不是那麼舒服,可是又要避免取9餘數時出現0的狀況,於是考慮先行 -1 取餘數後 +1 來避免遇9則0狀況。

_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
var addDigits = function(num) {
    return (num-1) % 9 + 1 ;
}
Min:188ms

var addDigits = function(num) {
    return (num < = 9) ? num : (num-1) % 9 + 1;
}
Min:176ms

_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/

C

_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
int addDigits(int num) {
    return (num < = 9) ? num : (num-1) % 9 + 1;
}
Min:4ms
_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/

Python

_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
class Solution(object):
    def addDigits(self, num):
        if (num <=9):
            return num
        else:
            return (num-1) % 9 + 1
Min:60ms

留言

這個網誌中的熱門文章

Leetcode:Number of 1 Bits