File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Sum the digits of an integer. Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Sum the digits of an integer." Watch "Sum the digits of an integer." New topic
Author

Sum the digits of an integer.

MaryEllen Volb
Ranch Hand

Joined: Jan 31, 2001
Posts: 35
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
huiying li
Ranch Hand

Joined: Feb 12, 2001
Posts: 68


SCJP
MaryEllen Volb
Ranch Hand

Joined: Jan 31, 2001
Posts: 35
Thanks....I'll try it!!! Mary Ellen
Pat Barrett
Ranch Hand

Joined: Jan 03, 2001
Posts: 63
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.
MaryEllen Volb
Ranch Hand

Joined: Jan 31, 2001
Posts: 35
Yes, it did help so much.....thanks....I wouldn't be getting thru my class if not for all the help I find here!!!

Mary Ellen
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Sum the digits of an integer.
 
Similar Threads
compute the sum of DIGITS in integer
sum of the digits in an integer
a problem with Palindromes please help..
problem with while loop
Sum Of Digits