• 13
• 16
• 27
• 9
• 9

Newb Java Question

This topic is 4200 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.