Sunday, December 13, 2020

Simple Java program to calculate the sum of all the digits of a number

 I just came across a simple yet an interesting challenge when I was attempting some online coding practices and thought to share it with you. Firstly would like to state that there can be many ways to separate each digit of the given number but I have used the most convenient way by converting it to String and processing.

Let me explain you the challenge.

  • An integer number is given and it should be at least a two digit number (15, 896 etc but not 9). Return -1 if this is not met.
  • If the above condition is met, then sum up all the digits of the number and return.
find my solution as below

public class DigitSum {
public static int sumDigits(int number){
int sum = 0;
if(number >= 10){
int numOfDigits = String.valueOf(number).length();

for(int i=0; i<numOfDigits ; i++){
sum += Character.getNumericValue(String.valueOf(number).charAt(i));
}
}else{
sum = -1;
}
return sum;
}
}

No comments:

Post a Comment