MDGSF Software Engineer

[算法学习][leetcode] 258 Add Digits

2017-09-05
mdgsf
Art

https://leetcode.com/problems/add-digits/description/

题目

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?

题目翻译

题目解析

参考答案

#include <iostream>
using namespace std;

/*
1    1
2    2
3    3
...
8    8
9    9
10   1
11   2
12   3
13   4
...
17   8
18   9
19   1
20   2
21   3
22   4
...
*/
class Solution {
public:
    int addDigits(int num)
    {
        if (num <= 9)
        {
            return num;
        }
        else
        {
            if (num % 9 == 0)
            {
                return 9;
            }
            else
            {
                return num % 9;
            }
        }
    }
};

int main()
{
    return 0;
}

weixingongzhonghao

Similar Posts

Comments