DEV Community

Saiful Islam
Saiful Islam

Posted on

Leetcode: 258

258. Add Digits

Solved
Easy
Topics
Companies
Hint

Question:

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

Example 1:

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:

Input: num = 0
Output: 0

Constraints:

0 <= num <= 231 - 1
Enter fullscreen mode Exit fullscreen mode

Soln:

#include<iostream>
using namespace std;

int main()
{
    int ans, num;
    cout << "Enter a number: " << endl;
    cin >> num;

    // Convert negative number to positive
    num = abs(num);

    // Repeat the process until num is a single digit
    while(num >= 10)
    {
        ans = 0;  // Reset ans for each iteration
        while(num > 0)
        {
            ans += num % 10;  // Add the last digit to ans
            num /= 10;        // Remove the last digit from num
        }
        num = ans;  // Set num to the sum of digits
    }

    cout << "Sum of digits until single digit is: " << num << endl;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)