sum of digits java

ht‮t‬ps://www.lautturi.com
sum of digits java

To find the sum of the digits of a number in Java, you can use a loop to extract each digit of the number and add it to a running total.

Here's an example of how to find the sum of the digits of a number using a loop:

int num = 12345;
int sum = 0;
while (num > 0) {
    sum += num % 10;
    num /= 10;
}
System.out.println(sum);  // prints 15

In this example, we're using the modulus operator (%) to extract the last digit of the number, and the division operator (/) to remove it. The loop continues until the number becomes 0, at which point the sum of the digits is printed.

You can also use the stream API introduced in Java 8 to find the sum of the digits of a number. Here's an example of how to do this:

int num = 12345;
int sum = String.valueOf(num).chars().map(Character::getNumericValue).sum();
System.out.println(sum);  // prints 15

In this example, we're using the chars method to create a stream of the characters of the number represented as integers, the map method to convert the characters to their numeric values, and the sum method to sum the elements of the stream.

You can find more information about the stream API and examples of how to use it in the Java documentation.

Created Time:2017-10-17 20:18:56  Author:lautturi