leetcode-258-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.

分析


找数学规律的一道题,比方说38,是3+8,而前面的3是30%9得到的,而11,1+1,前面的1是10%9得到的,

解决方案1(C++)


1
2
3
4
5
6
7
8
9
10
class Solution {
public:
int addDigits(int num) {
if(num%9 == 0 && num != 0){
return 9;
}else {
return num%9;
}
}
};

相关问题


(E) Happy Number

题目来源