This is the second solution to find the sum of digits of an integer value[s]. This solution defines a functional interface with single abstract method with lambda expression. The internal core logic converts an integer value to String, then parse each character to digit, and sums up each digit.
import java.util.Scanner;
//Define the functional interface with SAM 'SummingUpDigits'
interface SummingUpDigits {
public int sumdigits(int val);
}
public class SumofDigits {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner inpInt = new Scanner(System.in);
// Input an Integer
System.out.print("Enter an Integer=");
int numValue = inpInt.nextInt();
System.out.println("The given integer is=" + numValue);
/*
* Define the Lambda expression for the functional interface 'SummingUpDigits'
*/
SummingUpDigits SUD = ((intValue) -> {
int sumDigits = 0;
String strValue = String.valueOf(intValue);
int lenOfStr = strValue.length();
while (--lenOfStr >= 0)
sumDigits += Character.getNumericValue(strValue.charAt(lenOfStr));
return sumDigits;
});
System.out.println("The sum of digits in a given Integer is=" + SUD.sumdigits(numValue));
System.out.println("The sum of digits of '2841' value is=" + SUD.sumdigits(2841));
System.out.println("The sum of digits of '507' value is=" + SUD.sumdigits(507));
System.out.println("The sum of digits of '1004' value is=" + SUD.sumdigits(1004));
}
}
Output:
Enter an Integer=128
The given integer is=128
The sum of digits in a given Integer is=11
The sum of digits of '2841' value is=15
The sum of digits of '507' value is=12
The sum of digits of '1004' value is=5

Leave a comment