-10

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?

josh23
  • 1
  • 1
  • 6

4 Answers4

3

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).

Pshemo
  • 122,468
  • 25
  • 185
  • 269
1

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.

StackFlowed
  • 6,664
  • 1
  • 29
  • 45
0

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.

  • 3
    No need to use `Math.floor()`. Integer division automatically truncates. – Code-Apprentice Nov 04 '14 at 18:35
  • 1
    Also, what if the input has more than two digits? – Code-Apprentice Nov 04 '14 at 18:36
  • @Code-Apprentice, this is not a general function - just a simple method to solve the original request :) As for the integer division - I agree; but I think that explicitly requesting floor makes code more clear. (Of course, in a tight loop I wouldn't recommend doing it). – Aleksey Linetskiy Nov 04 '14 at 18:38
0

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);
sTg
  • 4,313
  • 16
  • 68
  • 115