March 06, 2024

Java Problem Solution: Find the Sum of Digits of a number in Java


public class DigitSumCalculator {
    public static void main(String[] args) {
        int number = 1234;
        System.out.println("Number: " + number);
        System.out.println("Sum of digits: " + calculateDigitSum(number));
    }

    // Function to find the sum of digits of a number in Java
    public static int calculateDigitSum(int number) {
        int sum = 0;
        while (number != 0) {
            sum += number % 10; // Add the last digit to the sum
            number /= 10; // Remove the last digit from the number
        }
        return sum;
    }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.