第一个是我自己的算法,第二个算法是我目前为止找到的最优解,引用了LeetCode评论区网友"止于至善"的C代码,
原链接:https://leetcode-cn.com/problems/reverse-integer/comments/
真的厉害,大家可以去看看
#include <bits/stdc++.h>
using namespace std;
// 重点在于判断是否溢出,不能大于 INT_MAX,不能小于 INT_MIN
//class Solution
//{
// public:
// int reverse(int x)
// {
// int sum = 0;
// int max = INT_MAX / 10;
// int min = INT_MIN / 10;
// int max_f = INT_MAX % 10;
// int min_f = INT_MIN % 10;
// while(x != 0)
// {
// int pos = x % 10;
// if(sum > max || (sum == max && x % 10 > max_f)
// || sum < min || (sum == min && x % 10 < min_f))
// {
// return 0;
// }
// sum = sum * 10 + pos;
// x /= 10;
// }
// return sum;
// }
//};
/*接下来要展示的网友"止于至善"的绝佳算法,真的佩服得五体投地,改最优解出现在评论区
链接:https://leetcode-cn.com/problems/reverse-integer/comments/
*/
class Solution
{
public:
int reverse(int x)
{
int max = 0x7fffffff, min = 0x80000000;//int的最大值最小值
long rs = 0;//用long类型判断溢出
for(; x; rs = rs*10+x%10,x/=10); //逆序,正负通吃,不用单独考虑负值
return rs>max||rs<min?0:rs;//超了最大值低于最小值就返回0
}
};
int main()
{
Solution sol;
cout<<sol.reverse(-201)<<endl;
cout<<sol.reverse(-30)<<endl;
cout<<sol.reverse(9990)<<endl;
cout<<sol.reverse(9900)<<endl;
return 0;
}