# Newb Java Question

This topic is 4413 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I need to take an integer such as 1234 and add the digits of the integer. After declaring the integer, how do I use specific digits of it? For example, I have int x = 1234. I need int y to equal the sum of the digits, in this case, 10. Help? I'd really appreciate it. [Edited by - furinto on September 17, 2006 9:31:49 AM]

##### Share on other sites
This sounds a bit like homework, which is against our policies for this forum. Have you tried thinking about the steps you would take to get the values you want?

Some things to consider:

1.) If you only have one digit, the answer is that digit (e.g., the sum of the digits of the number 7 is 7).

2.) If you have n digits, the answer is the last digit plus the sum of the remaining n-1 digits.

Note that statement [2] suggests that an easy recursive solution; just take the last digit and re-call your own method with the shortened number. For instance, if the number is 67281, you would call SumOfDigits(67281), which would result in a call to SumOfDigits(1) + SumOfDigits(6728), which would become 1 + SumOfDigits(8) + SumOfDigits(672), and so on.

hope that helps,

##### Share on other sites
You should do a little research on the % and / operators.

That should get you started with coming up with an algorithm.

-JR

##### Share on other sites
Two ways I can think off.

	public int addUp(int i)	{		int num =0;		int div = 1;		if(i == 0) return num;		while(true)		{			if(i / div < 10)			{				num += i /div;				num += addUp(i - (div * (i / div)));				break;			}			div *= 10;		}		return num;	}

	public int sAddUp(int i)	{		String s = Integer.toString(i);		int num = 0;				for(int t=0; t< s.length();t++)			num += Character.digit(s.charAt(t),10);		return num;	}

Both these functions should return the sum of the digits in the integer passed in to them. There is probably better ways but this is all I could think of at the top of my head.

[Edited by - clearz on September 17, 2006 7:48:48 AM]

##### Share on other sites
0) "Newb questions" are best placed in For Beginners (it appears at the top of the forum listing for a reason; so it will be noticed).

1) We don't do homework here.

3) How do you access digits of a number when you do it yourself on paper? What, just look at it? OK, smart guy, how will you get digits of the number as represented in a different base? :) Think about how bases and numerical representations work, and you should be able to figure out how you *really* extract this information (without just "looking").

1. 1
2. 2
3. 3
Rutin
22
4. 4
5. 5

• 11
• 18
• 14
• 9
• 9
• ### Forum Statistics

• Total Topics
632929
• Total Posts
3009280
• ### Who's Online (See full list)

There are no registered users currently online

×