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

Three Equal Parts Problem

LeetCode 927. You are given an array arr which consists...

Surface Area Of 3D Shapes Problem

LeetCode 892. You are given an n x n grid...

Super Palindromes Problem

LeetCode 906. Let’s say a positive integer is a super-palindrome...

Smallest Range I Problem

LeetCode 908. You are given an integer array nums and...

Projection Area Of 3D Shapes Problem

LeetCode 883. You are given an n x n grid...

Prime Palindrome Problem

LeetCode 866. Given an integer n, return the smallest prime...