DEV Community

Discussion on: Reverse an Integer - Code Challenge

Collapse
 
smartcodinghub profile image
Oscar • Edited

You can do this with mathematical operations that are way faster and simpler. Example in C#:

int number = -321; // Number
int sign = Math.Sign(number); // Sign
number *= sign; // Abs

int n = 0; // Accumulator
do
{
   /* '* 10' moves the accumulator the the left to accumulate one more digit. 
    * Then, '% 10' extracts the last digit */
    n = n * 10 + number % 10;
} while ((number /= 10) > 0); // '/ 10' removes the last digit

n *= sign; // Add the sign to the already reversed number

So, with -321:

  1. Take the sign (-) and the abs (321).
  2. The accumulator is 0.
    1. Move left: n * 10 = 0. Digit: number % 10 = 1. Remove: number / 10 = 32.
    2. Move left: n * 10 = 10. Digit: number % 10 = 2. Remove: number / 10 = 3.
    3. Move left: n * 10 = 120. Digit: number % 10 = 3. Remove: number / 10 = 0.
  3. Then, we have 321 and multiply by the sign(-) and have -123.