0

有没有比这更好的方法来反转整数?

    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;
    }
4

2 回答 2

3

有没有比这更好的方法来反转整数?

好吧,在编程中,“更好的方式”之类的东西并没有很好的定义。换句话说,它可能意味着很多事情。它可以是更好的性能,更好的内存使用等。

但是,最重要的是代码没有错误

您的代码并非在所有情况下都没有错误。

考虑一个 INT_MAX 为 41 的晦涩系统,然后使用值 34 调用您的函数。

它会失败。

问题是您的溢出检查忽略了乘以 10x%10添加的部分。换句话说 - INT_MAX 可能有一个不会溢出的值,但是一旦添加它就会溢出。out*10x%10

于 2021-01-06T06:41:54.603 回答
1

是的,在 C++ 的情况下,有一个非常简单的方法。

#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;
}

这在代码的简单性和可理解性方面更好。它的性能方面,我猜你原来的实现可能会更好。

于 2021-01-06T07:15:49.193 回答