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.
===================================================================
题目链接:https://leetcode.com/problems/add-digits/
题目大意:计算num各个位的数字之和,直到最终结果是一位数。
思路:递归计算。
参考代码:
class Solution {
public:
int addDigits(int num) {
if ( num < 10 )
return num ;
int ans = 0 ;
while ( num )
{
ans += ( num % 10 ) ;
num /= 10 ;
}
return addDigits ( ans ) ;
}
};