Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum digits of an integer in java?

Tags:

I am having a hard time figuring out the solution to this problem. I am trying to develop a program in Java that takes a number, such as 321, and finds the sum of digits, in this case 3 + 2 + 1 = 6. I need all the digits of any three digit number to add them together, and store that value using the % remainder symbol. This has been confusing me and I would appreciate anyones ideas.

like image 507
Shane Larsen Avatar asked Nov 24 '14 01:11

Shane Larsen


People also ask

How do you sum integers in Java?

By Using Integer.sum() Method The Integer class provides the sum() method. It is a static method that adds two integers together as per the + operator. It can be overloaded and accepts the arguments in int, double, float, and long.

How do you calculate sum of digits?

We can calculate the sum of digits of a number by adding a number's digits while ignoring the place values. So, if we have the number 567, we can calculate the digit sum as 5 + 6 + 7, which equals 18.

How do you find the sum of numbers from 1 to 100 in Java?

This article will demonstrate via examples how to resolve the Java Program To Find The Sum Of First 100 Numbers error . int sum = 0; for(int i = 1; i <= 100; i++) { sum = sum + i; } System. out. println("Sum of first 100 numbers is : " + sum);


1 Answers

public static void main(String[] args) {
        int num = 321;
        int sum = 0;
        while (num > 0) {
            sum = sum + num % 10;
            num = num / 10;
        }
        System.out.println(sum); 
}

Output

6
like image 137
Ankur Singhal Avatar answered Sep 28 '22 09:09

Ankur Singhal