258. Add Digits

来源:互联网 发布:电脑屏幕录像软件推荐 编辑:程序博客网 时间:2024/06/06 02:48

题目来源【Leetcode】

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?

这道题我用的就是循环,后来在网上看到这是一个有规律的题

我的代码:

class Solution {public:    int addDigits(int num) {        while(num > 9){             int sum = 0;             while(num != 0){                 sum += num%10;                 num = num/10;             }            num = sum;        }        return num;    }};

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

class Solution {
public:
int addDigits(int num) {
if (num <= 0) return 0;
return (num % 9) == 0 ? 9 : num % 9;
}
};

原创粉丝点击