DIGIT SUM CHALLENGE
Write a method with the name sumDigits that have one int parameter called number. If the parameter is >=10 then the method should process the number and return the sum of all digits, otherwise, return -1 to indicate an invalid value. The numbers from 0-9 have 1 digit so we don't want to process them, also we don't want to process negative numbers, so also return -2 for negative numbers. For example, calling the method sumDigit(125) should return 8 since 1+2+5 = 8. Calling the method sumDigit(1) should return -1 as per the requirements described above. Add some codes to the main method to test out the sumDigits method to determine that it is working correctly for valid and invalid values passed as arguments.
HINT
Use n%10 to extract the least-significant digit.
Use n=n/10 to discard the least-significant digit
The method needs to be static like other methods so far in the course.
Soln:
package com.cnc;
public class Main {
public static void main(String[] args) {
System.out.println(sumDigits(99999));
}
public static int sumDigits(int number){
if(number<10){
return -1;
}
int sum = 0;
//125 ----> (125/10=12)---->(12*10=120)----->(125-120=5)
while (number>0){
//extract the-least significant digit
int digit = number%10;
sum += digit;
//drop least-sigificant digit
number /=10;//same as number = number /10;
}
return sum;
}
}