Register to reply

Java int addition - the long way

by NiaSphinx
Tags: addition, int, java
Share this thread:
NiaSphinx
#1
Oct5-09, 02:47 AM
P: 4
Hi guys,

I'm trying to figure out a way to split up integers so I can do addition the old school way in Java.
E.g.:
1234
1234
+_____
2468

So you know start at the 4's and then add them up and move left etc.
Does anyone have any ideas on how I access the different digits of an int?

Thanks
Phys.Org News Partner Science news on Phys.org
Wildfires and other burns play bigger role in climate change, professor finds
SR Labs research to expose BadUSB next week in Vegas
New study advances 'DNA revolution,' tells butterflies' evolutionary history
CompuChip
#2
Oct5-09, 03:27 AM
Sci Advisor
HW Helper
P: 4,300
I don't know if there is some nice routine for this, but there is always the oldfashioned dirty way: to access the 10n digit (i.e. for n = 0 you get the units, for n = 1 the tens, etc) you can integer-divide by 10n and then take the result modulo 10.
For example:

1234 / 100 = 12 (as integer division produces an integer by chopping off the decimal part)
12 % 10 = 2
NiaSphinx
#3
Oct5-09, 03:36 AM
P: 4
Ah that does sound like a good way of doing it.
Can it work the same if the base is not 10?

CompuChip
#4
Oct5-09, 05:51 AM
Sci Advisor
HW Helper
P: 4,300
Java int addition - the long way

I suppose in base b, one can still obtain the digits at the nth position (starting from n = 0 on the right) of a number N as

[tex]\operatorname{digit}_n(N) = \left[ N / b^n \right] \text{ mod } b [/tex]
where the square brackets denote the floor of the division.


Register to reply

Related Discussions
Question about the sun and the earth long long ago. Astronomy & Astrophysics 3
Java GUI Programming & Computer Science 3
My first sports session in a long long time (groan) General Discussion 14
How long is Ph.D qualifying exam? How long should I take for preparation? Academic Guidance 2
My school seems to mainly teach java Computing & Technology 21