Thursday, 10 January 2013

Digit sum VS Sum of digits + JAVA Code


Sum Of Digits : It is the sum of all the digits of a number(given) and we are list bothered about the result.
Eg.  Given Number   ->   5982
       Sum of digits     :    5+9+8+2 =24             Result is 24
       Note
       Here, result can be a single digit or multiple digit.

Digit Sum : It is also the sum of digits but we have to add the digits till it become a single digit number.
Eg.  Given Number->  5982
       Digit sum       :   5+9+8+2 = 24 but we have to sum the digits again as 24 is not a single digit
                                2+4=6                          Result is 6
       Note:
       Here, final result will always be as single digit number.
(Shortcut to get Digit sum)
Digit sum is the remainder we get after dividing the number by 9
eg.   5982%9  = 6    where % specifies modulus used to find remainder.    


JAVA Code for Sum of Digits

public class sumOfDigits
{
public static void main (String args[])
{
int number =5982;
int sum=0;
int variable;
while(number>0)
{
variable=number%10;
sum=sum+variable;
number=number/10;
}
System.out.println("Sum of Digits is : "+sum);
}
}  


JAVA Code for Digit Sum


public class DigitSum 
{
public static void main (String args[])
{
int number =5982;
int sum=0;
int variable;
while(number>9)
{
while(number>0)
{
variable=number%10;
sum=sum+variable;
number=number/10;
}
number=sum;
sum=0;
}
System.out.println("Sum of Digits is : "+number);
}
}             
       

No comments:

Post a Comment