Leetcode P0258"Add Digits" 题解

2021/04/13 Leetcode

博文中会简要介绍Leetcode P0258题目分析及解题思路。

“Add Digits”是一道比较简单的题目,主要思路就是模拟一遍题目要求即可。

Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.

以下是Java的题解代码实现。

class Solution {
    public int addDigits(int num) {
        while (num/10 != 0) {
            int sum = 0;
            while (num != 0) {
                sum += num%10;
                num /= 10;
            }
            
            num = sum;
        }
        
        return num;
    }
}

以下是C++的题解代码实现。

class Solution {
public:
    int addDigits(int num) {
        while (num/10 != 0) {
            int sum = 0;
            while (num != 0) {
                sum += num%10;
                num /= 10;
            }
            
            num = sum;
        }
        
        return num;
    }
};

Search

    Table of Contents