Lets first figure out the logic of getting digits of a number, once we get the digit we can count them and also find addition.
suppose we have a digit= 543374. lets figure out it as;
Step 1:
reminder = 543374%10 = 4
digit =543374/10 =54337 (1 digit)
Step 2:
reminder = 54337%10 = 7
digit = 54337/10 =5433 (2 digit)
Step 3:
reminder = 5433%10 = 3
digit =5433/10 =543 (3 digit)
Step 4:
reminder = 543%10 = 3
digit =543/10 =54 (4 digit)
Step 5:
reminder = 54%10 = 4
digit =54/10 =5 (5 digit)
Step 6:
reminder = 5%10 = 5
digit =5/10 =0 (6 digit)
now at last we get zero (0). it goes until we get quotient as zero. then count the number of steps, here are 6 steps so number of digits is here 6.
Program:
import java.util.*;
class Main
{
int num;
Scanner scan = new Scanner(System.in);
public void length_sum_digits(){
System.out.println("Please enter a number.");
num = scan.nextInt();
int sum = 0, count = 0;
while(num > 0){
sum += num%10;
num = num/10;
count++;
}
System.out.println("Number of digits:"+ count);
System.out.println("Summation of digits of number is "+sum);
}
public static void main(String[] args) {
Main obj = new Main();
obj.length_sum_digits();
}
}
Output:
