Add Digits Problem


Description

LeetCode Problem 258.

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

Example 1:

1
2
3
4
5
6
Input: num = 38
Output: 2
Explanation: The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2 
Since 2 has only one digit, return it.

Example 2:

1
2
Input: num = 0
Output: 0

Constraints:

  • 0 <= num <= 2^31 - 1


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
    int addDigits(int num) {
        int sum = 0;
        while (num > 9) {
            while(num) {
                sum += (num % 10);
                num /= 10;
            }
            num = sum;
            sum = 0;
        }
        return num;
    }
};




Related Posts

Count Primes Problem

LeetCode 204. Given an integer n, return the number of...

Basic Calculator Problem

LeetCode 224. Given a string s representing a valid expression,...

Basic Calculator II Problem

LeetCode 227. Given a string s which represents an expression,...

Add Digits Problem

LeetCode 258. Given an integer num, repeatedly add all its...

Factorial Trailing Zeroes Problem

LeetCode 172. Given an integer n, return the number of...

Rotate Image Problem

LeetCode 48. Determine if a 9 x 9 Sudoku board...