问题描述:
Given a non-negative integer num
, repeatedly add all its digits until the result has only one digit.
示例:
Given num = 38
, the process is like: 3 + 8 = 11
, 1 + 1 = 2
. Since 2
has only one digit, return it.
问题分析:
其中,num最终变成的个位数在0-9之间,经过简单的计算,你会发现,num值为9,18,27,36......时,最终的个位数为9;当num为0时,个位数才是0;其他情况下,个位数的值均为num % 9.
过程详见代码:
class Solution {
public:
int addDigits(int num) {
if(num == 0) return 0;
if(num % 9 == 0) return 9;
return num % 9;
}
};