Add Digits

Add Digits

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

LeetCode Problem: Link | Click Here

class Solution {
    public int addDigits(int num) {
        // Flag to check if the number is a single digit
        boolean singleDigit = true;
        // Variable to store the sum of the digits
        int sum = 0;

        // Loop through the digits of the number and add them up
        while (num != 0) {
            sum += num % 10; // Add the last digit to the sum
            num /= 10; // Move to the next digit
        }

        // Check if the sum is still more than one digit
        if (sum < 10) {
            singleDigit = false; // Update the flag if it's not a single digit
        }

        // Store the sum in another variable for further processing
        int num1 = sum;

        // Continue processing until the sum becomes a single digit
        while (singleDigit) {
            // If the sum is still more than one digit, break it down again
            if (sum > 9) {
                sum = 0;
                // Calculate the sum of the digits of the current sum
                while (num1 != 0) {
                    sum += num1 % 10; // Add the last digit to the sum
                    num1 /= 10; // Move to the next digit
                }
            }

            num1 = sum; // Store the new sum for further calculation

            // If the sum is now a single digit, exit the loop
            if (sum <= 9) {
                singleDigit = false; // Update the flag as it's now a single digit
            }
        }

        // Return the final sum which is now a single digit
        return sum;
    }
}

Did you find this article valuable?

Support Gulshan Kumar by becoming a sponsor. Any amount is appreciated!