how to find sum of the digit of the numbers in java

www.laut‮t‬uri.com
how to find sum of the digit of the numbers in java

To find the sum of the digits of a number in Java, you can use a loop to iterate over the digits of the number and add them together.

Here's an example of how to find the sum of the digits of a number in Java:

int number = 12345;
int sum = 0;

while (number > 0) {
  sum += number % 10;
  number /= 10;
}

System.out.println("The sum of the digits is " + sum);

In the above example, a variable called number is defined and initialized with the value 12345. A variable called sum is initialized with the value 0.

A while loop is used to iterate over the digits of the number. The loop continues as long as the value of number is greater than 0.

Inside the loop, the sum variable is updated by adding the last digit of the number (obtained using the modulo operator %) to its current value. The number variable is then updated by dividing it by 10 using integer division (/). This removes the last digit from the number.

After the loop completes, the sum variable contains the sum of the digits of the number and it is printed to the console.

Keep in mind that this example only works for positive integers. If you need to handle negative integers or non-integer values, you may need to use a different approach.

Created Time:2017-11-01 20:42:52  Author:lautturi