-1

Trying to figure out how to reconstruct the number once it's pulled apart...Use the modulus operator to swap digit pairs. For instance a method call swapDigitPairs(482596) would return 845269. It needs to be done without using an array or a string. If the method got passed an integer with an odd number of digits the leftmost doesn't move.

Edit: The 9 and 6 are swapped, the 2 and 5 are swapped, and the 4 and 8. I understand how to pull the numbers apart, but I'm looking for some ideas how to put them together without a string or an array. Any ideas appreciated

cluv
  • 620
  • 6
  • 11

2 Answers2

1

Here is a scratch pseudo-code - hopefully helps

{
    int i = 0x842569;

    Do for each byte
    {
          for byte0
          {

               int  byte0Swapped = swapNibble (i & 0xFF);

                i = (i & 0xFFFFFF00) | byte0Swapped ;
          }
    }
}
abRao
  • 2,787
  • 1
  • 25
  • 37
0

Haskell:

swap num = 
  swap' num 1
    where swap' num factor =
            let a = mod num 10
                b = mod (div num 10) 10
            in next + factor * (10 * a + b)
                where next = if num == 0 
                                then 0
                                else swap' (div num 100) (100 * factor)

*Main> swap 482596
845269

גלעד ברקן
  • 23,602
  • 3
  • 25
  • 61