Leetcode: Add Digits

来源:互联网 发布:适合手机编程的输入法 编辑:程序博客网 时间:2024/05/01 21:09

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?

不应该是循环的解法,找规律,每9个数最终的结果重复从1到9。wiki上说这叫digital root,对应9的最大整数倍后面的第几个数,有相应的公式。关键是找到这个规律。

class Solution {public:    int addDigits(int num) {        return  num - (num - 1) / 9 * 9;    }};

再,

class Solution {public:    int addDigits(int num) {        return  (num - 1) % 9 + 1;    }};


0 0