Pages

Sum of individual digits of a number

Sum of individual digits of a number

  • We can find the sum of individual digits of a given number using loop , java 8 etc.,.

public class SumOfDigits {
public static void main(String[] args) {
int number = 111111;
int p;
int sum = 0;
while (number != 0) {
p = number % 10;
sum = sum + p;
number = number / 10;
}
System.out.println("sum of individual digits of given number=" + sum);


int n = 123;

//sum of individual digits of given number using java 8
int sumOfDigits = String.valueOf(n).chars().map(Character::getNumericValue).sum();
System.out.println("sum of individual digits of given number using map=" + sumOfDigits);

}
}
Output:
Sum of individual digits of a number
Sum of individual digits of a number
Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.