题目:
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.
翻译:
给定一个非负整数 num,重复叠加这个整数的每一位直到获得的结果是一个只有一位的数字。
举例:
给定 num = 38,整个过程像这样:3 + 8 = 11
, 1 + 1 = 2
。因为 2 是一个只有一位的数字,返回它。
思路:
设定 sum=0,sum不断加上 num%10,然后 num=num/10。
C++代码(Visual Studio 2017):
#include "stdafx.h"
#include <iostream>
using namespace std;
class Solution {
public:
int addDigits(int num) {
while (num / 10 > 0) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num = num / 10;
}
num = sum;
}
return num;
}
};
int main()
{
Solution s;
int result;
int num=38;
result = s.addDigits(num);
cout << result;
return 0;
}