Search code examples
cintegerreverse

Reverse integers above 199


I am solving a problem in C which reverses the integer provided to it.

Code:

int reverse(int x) {
    int i, t = 1, y = 0, neg = 0;
    if (x < 0) {
        neg = 1;
        x = -1 * x;
    }
    while (x / t > 1) {
        t = t * 10;
    }
    int p = t;
    while (t >= 1) {
        int d = x / t;
        y = y + p * d / t;
        x = x - d * t;
        t = t / 10;
    }
    if (neg == 1) {
        y = -1 * y;
    }
    return y;
}

For some reason the program works incorrectly if x is over 199.

In the first while loop, it takes d as 0, and hence an extra 0 is added to the end of the reversed integer.

I know I can just code it to divide by 10 if the input is over 200, but why it happens and is there any alternate solution possible?


Solution

  • The problem is in the statement:

    while(x/t>1)
    

    You are raising y more than the power that suits your algorithm.

    It should work if you change the condition like this:

    while(x/t>=10)
    

    And here is an alternate solution, which is way simpler than what you're trying to do.

    Steps:

    • 1 - Extract the first digit to the right.
    • 2 - Multiply it by 10 and add it to your reversed variable, as if you're pushing it to the left.
    • 3 - Divide your number by 10 to remove the digit you just used.
    • 4 - Repeat until your number is equal to 0.
    long reverse_modified(long number)
    {
        long rem =0 , reversed = 0;
    
        /*4*/while (number != 0) 
        {
            /*1*/rem = number % 10;
            /*2*/reversed = reversed * 10 + rem;
            /*3*/number /= 10;
        }
        
        return reversed;
    }