How to Perform Sum of the Digits in a Given Number in Java
In this blog, we will learn about how to sum of the digits in a given number in Java. This will be asked in the most of the interviews.This can be implemented using the below way:
In the below snippet, we have done the following:
- Created the below variables of int type
- Number (assigned it with some value)
- Sum (assigned it with some value)
- Reminder
- By using while loop until the number value is greater than 0. we have done the below:
- Performed modular division of the number and stored the result in the reminder
- Stored the reminder value in the Sum
- Performed Division operation of the number and stored the result in the Number
public class SumOfDigitsInANumber { public static void main(String[] args) { int number=2587, reminder, sum = 0; while(number>0) { reminder = number % 10; sum = sum + reminder; number = number / 10; } System.out.println("The sum of digits in a given number is:" +sum); } }
Output: ------- The sum of digits in a given number is:22
Please watch the Youtube video for better understanding.