Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Java int addition - the long way

  1. Oct 5, 2009 #1
    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
     
  2. jcsd
  3. Oct 5, 2009 #2

    CompuChip

    User Avatar
    Science Advisor
    Homework Helper

    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
     
  4. Oct 5, 2009 #3
    Ah that does sound like a good way of doing it.
    Can it work the same if the base is not 10?
     
  5. Oct 5, 2009 #4

    CompuChip

    User Avatar
    Science Advisor
    Homework Helper

    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.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Java int addition - the long way
  1. Why are Ints 32 bits? (Replies: 8)

Loading...