0

Is there any better way to reverse an integer than this?

    int reverse(int x) {
        int out=0;
        while(x)
        {
            if(out > INT_MAX/10 || out < INT_MIN/10){return 0;}
            else{
                out = out*10 + x%10;
                x /= 10;
            }
        }
        return out;
    }
Ghiri Hari
  • 71
  • 1
  • 6
  • 1
    Please note that C and C++ are different languages. Do not tag both as the best solution may be different for the two. – kaylum Jan 06 '21 at 06:09
  • 6
    Define reverse an integer. Reverse the string representation of an integer? Because numbers don't have an obvious reverse function. Honestly I'd probably convert it to a string, reverse that, then convert it back to an int, unless you really needed performance out of it. – Gabe Sechan Jan 06 '21 at 06:15
  • The way you check for `out` overflow is wrong. – Evg Jan 06 '21 at 06:39

2 Answers2

3

Is there any better way to reverse an integer than this?

Well, in programming something like "better way" isn't well defined. In other words it can mean a number of things. It can be better performance, better memory usage, etc.

However, the most important thing is that the code is bug free.

Your code isn't bug free in all cases.

Consider an obscure system where INT_MAX is 41 and then call your function with the value 34.

It will fail.

The problem is that your overflow check ignores the x%10 part which is added after the multiplication by 10. In other words - INT_MAX could have a value where out*10 won't overflow but once you add x%10 it will overflow.

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
1

Yes, in case of C++ there is a very simple way.

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>

int Reverse(int x)
{
    // Read number to a string stream
    std::stringstream ss;
    ss << x;

    // Take the string in stringstream
    std::string s = ss.str();
    std::reverse(s.begin(), s.end());
    ss.str(s);

    // Take the number from reversed string.
    int ret;
    if (!(ss >> ret)) ret = 0;

    return ret;
}

int main()
{
    std::cout << Reverse(1234); // Or any number for test.
    return 0;
}

This is better in terms of simplicity and understandability of code. It terms of performance, I guess your original implementation could be better.