Java Java int addition - the long way

  • Thread starter Thread starter NiaSphinx
  • Start date Start date
  • Tags Tags
    Addition Java
AI Thread Summary
To split integers for addition in Java, the discussion highlights a method to access individual digits of an integer. The approach involves using integer division and the modulo operation. Specifically, to retrieve the nth digit of a number, you can divide the integer by 10 raised to the power of n and then apply the modulo operation with 10. For example, to access the units digit, you would divide by 10^0 (which is 1) and take the result modulo 10. This method can also be adapted for different bases; for base b, the formula for obtaining the nth digit is given as digit_n(N) = [N / b^n] mod b, where the brackets indicate the floor of the division. This technique allows for traditional columnar addition by processing digits from right to left.
NiaSphinx
Messages
4
Reaction score
0
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
 
Technology news on Phys.org
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
 
Ah that does sound like a good way of doing it.
Can it work the same if the base is not 10?
 
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

\operatorname{digit}_n(N) = \left[ N / b^n \right] \text{ mod } b
where the square brackets denote the floor of the division.
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I had a Microsoft Technical interview this past Friday, the question I was asked was this : How do you find the middle value for a dataset that is too big to fit in RAM? I was not able to figure this out during the interview, but I have been look in this all weekend and I read something online that said it can be done at O(N) using something called the counting sort histogram algorithm ( I did not learn that in my advanced data structures and algorithms class). I have watched some youtube...
Back
Top