###Mark:
INT_MAX,INT_MIN由标准头文件<limits.h>定义。
INT_MAX=2^31-1(2,147,483,647)
INT_MIN=-2^31(-2,147,483,648)
题解
这道题主要难点是要考虑溢出的问题。
数学解法:
#include "iostream"
#include "limits.h"
class Solution
{
public:
int reverse(int x)
{
int res=0;
int pop;
while(x!=0)
{
pop=x%10;
x=x/10;
if(res>INT32_MAX/10 || res==INT32_MAX && pop>(INT32_MAX-INT32_MAX/10))
return 0;
if(res<INT32_MIN/10 || res==INT32_MIN &&pop<(INT32_MIN-INT32_MIN/10))
return 0;
res=res*10+pop;
}
return res;
}
};
这里发现几个问题:
- 不可以写
if(res*10>INT32_MAX || pop>(INT32_MAX-res*10))
,会直接导致溢出。 whlie(x)
和while(x!=0)
执行效率相差甚远,前者0ms,超过100% 代码,后者4ms,超过78%代码。- 还有一种说法是 ,针对这道题目来说,
if(res*10>INT32_MAX || res==INT32_MAX && pop>(INT32_MAX-res*10))
这个条件,可以简化成if(res*10>INT32_MAX)
,因为对于本题目给定为int型,范围是-2147483648到2147483647,所以当res==INT32_INT
时,最后加入的一位为原来数字的首位,也就是说pop只可能在-2~2之间,不会大于7或小于-8。
题解2 转换成字符串 然后反转字符串
to_string
函数:将数值转换为字符串,返回对应的字符串形式。
#include "iostream"
#include "limits"
#include "string"
using namespace std;
class Solution {
public:
int reverse(int x) {
if(x==INT32_MIN) return 0;
int flag=1;
if(x<0)flag=-1;
x=abs(x);
string s=to_string(x);
for(int i=0,j=s.size()-1;i<j;i++,j--)
{
swap(s[i],s[j]);
}
long long ans;
for(auto k=s.begin();k!=s.end();k++)
ans=(ans*10)+*k-'0';
if(ans>INT32_MAX) return 0;
else return (int)ans*flag;
}
};
以下代码来自:
作者:pinku-2
链接:https://leetcode-cn.com/problems/reverse-integer/solution/zheng-shu-fan-zhuan-cshi-xian-liang-chong-jie-fa-z/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution
{
public:
int reverse(int x)
{
long result; //利用long避免溢出
if (x == INT_MIN)
{
return 0;
}
if (x < 0)
{
return -reverse(-x);
}
stringstream ss;
ss << x;
string tmpStr;
ss >> tmpStr;
int tmpStrSize = int(tmpStr.size());
string resultStr;
for (int index = tmpStrSize - 1; index >= 0; index--)
{
resultStr.push_back(tmpStr[index]);
}
ss.clear(); //使用前记得clear
ss << resultStr;
ss >> result;
if (result > INT_MAX)
{
return 0;
}
return int(result);
}
};
stringstream常见用法介绍
https://blog.youkuaiyun.com/liitdar/article/details/82598039