I want to add the digits of4 numbers of 1 or 2 digits using Java.
i1=2
i2=33
i3=12
i4=10
Result : 12 (2+3+3+1+2+1+0)
How could I do that?
I want to add the digits of4 numbers of 1 or 2 digits using Java.
i1=2
i2=33
i3=12
i4=10
Result : 12 (2+3+3+1+2+1+0)
How could I do that?
Here are some hints you may need:
1) If you use /
on arguments which will be integers then your result will also be integer.
Example:
int x = 7/2;
System.out.println(x);
output: 3
(not 3.5
)
So to get rid of last digit of integer all you can do is divide this number by 10 like
int x = 123;
x = x/10;
System.out.println(x);
Output: 12
2) Java also have modulo operator which returns reminder from division, like 7/2=3
and 1
will be reminder. This operator is %
Example
int x = 7;
x = x % 5;
System.out.println(x);
Output: 2
because 7/5=1 (2 remains)
So to get last digit from integer you can simply use % 10
like
int x = 123;
int lastDigit = x%10;
System.out.println(lastDigit);
Output: 3
Now try to combine this knowledge. Get last digit of number, add it to sum, remove this last digit (repeat until will have no more digits).
You want to do it like this:
public static void main(String[]args){
int num=1234,sumOfDigits=0;
while(num!=0){
sumOfDigits+=num%10;
num/=10;
}
System.out.println("Sum of digits is : " + sumOfDigits);
}
Things to understand % give the remainder of the number so when you do 1234%10 it gives 4. That is the last digit.
num/=10 means num=num/10; so this will 1234/10 will be 123 and not 123.4 as this is int by int division.
Create a function that will calculate the sum of digits :
int getDigitSum(int n) {
return Math.floor(n/10) + n % 10;
}
Then use it on each value and sum the results.
Please note that I wrote this method only to work with numbers less than 100. You can easily create more generic method if needed.
I gave a try to achieve your target on a paper though.:-).Please Try this
int addition=0;
int num=243;
while(num>9){
int rem;
rem=num%10;
addition=addition+rem;
num=num/10;
if(num<9) {
addition+=num;
num=addition;
addition=0;
}
}
System.out.println(num);