# Sum the digits of an integer.

MaryEllen Volb

Ranch Hand

Posts: 35

posted 16 years ago

I have already gotten one good response to this one, but now I can't understand how to extract the digits so I can sum them together (2 + 3 + 4 =9). Anyone got any great idea?

Here's the code I already got:

public class Test{

public static void main(String[] args){

int i = 234;

sumDigits(i);}

private static void sumDigits(int digits){System.out.println("digits before calculation: " + digits);int sum = 0;

sum += digits % 10;

digits /= 10;

System.out.println("sum: " + sum);System.out.println("digits after calculation: " + digits);

}} Thanks!!!Mary Ellen

Here's the code I already got:

public class Test{

public static void main(String[] args){

int i = 234;

sumDigits(i);}

private static void sumDigits(int digits){System.out.println("digits before calculation: " + digits);int sum = 0;

sum += digits % 10;

digits /= 10;

System.out.println("sum: " + sum);System.out.println("digits after calculation: " + digits);

}} Thanks!!!Mary Ellen

Pat Barrett

Ranch Hand

Posts: 63

posted 16 years ago

- 1

Hello,

The first thing is to separate the digits. If you take a 3 digit number and divide by 100, your answer will be a single digit representing the hundreds place. Now, if you take that same 3 digit number and get the modulus of a division by 100, you will be left with the tens and units places, represented as a 2 digit number. Take that 2 digit number, divide by ten and you'll have the 10's place, the modulus of the 2 digit number divided by 10 will be the units place.

Let's try 123..

123 / 100 = 1 ( the hundreds place )

123 % 100 = 23 ( the remainder )

23 / 10 = 2 ( the tens place )

23 % 10 = 3 ( the units place )

Sum up the hundreds, tens & units and you'll have your answer.

or.....

hth.

Pat B.

The first thing is to separate the digits. If you take a 3 digit number and divide by 100, your answer will be a single digit representing the hundreds place. Now, if you take that same 3 digit number and get the modulus of a division by 100, you will be left with the tens and units places, represented as a 2 digit number. Take that 2 digit number, divide by ten and you'll have the 10's place, the modulus of the 2 digit number divided by 10 will be the units place.

Let's try 123..

123 / 100 = 1 ( the hundreds place )

123 % 100 = 23 ( the remainder )

23 / 10 = 2 ( the tens place )

23 % 10 = 3 ( the units place )

Sum up the hundreds, tens & units and you'll have your answer.

or.....

hth.

Pat B.

MaryEllen Volb

Ranch Hand

Posts: 35