欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

258. Add Digits

程序员文章站 2022-06-04 10:44:51
...

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
Example:
Input: 38
Output: 2
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
Since 2 has only one digit, return it.


题解:

#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::to_string;

int AddDigits(int num);

int Sum(int num);

int main(int argc, const char* argv[]) {
    int num = 38;
    cout << AddDigits(num) << endl;

    system("pause");
    return 0;
}

int AddDigits(int num) {
    do {
        num = Sum(num);
    } while (to_string(num).size() != 1);
    return num;
}

int Sum(int num) {
    if (num == 0)
        return 0;

    return num % 10 + Sum(num / 10);
}
相关标签: Add Digits