题目
leetcode 7. Reverse Integer 整数反转
代码
提前判断溢出
#include <cstring>
#include <string>
#include <iostream>
using namespace std;
//-2,147,483,648 到 2,147,483,647
int reverse(int x) {
int res=0;
int pop=0;
while(x!=0){
pop=x%10;
x/=10;
//溢出判断
if(res>INT_MAX/10||(res==INT_MAX/10&&pop>7))return 0;
if(res<INT_MIN/10||(res==INT_MIN/10&&pop<-8))return 0;
res=res*10+pop;
}
return res;
}
int main() {
// int a = reverse(123);
// int a = reverse(-123);
// int a = reverse(120);
int a = reverse(1534236469);
cout<<a;
// int b = -12%10;
// cout<<b; //-2
return 0;
}
反转完成后溢出判断
#include <cstring>
#include <string>
#include <iostream>
using namespace std;
int reverse(int x) {
string xs = to_string(x);
string ans;
if(!xs.empty()&&xs[0]=='-'){
ans+='-';
xs=xs.substr(1);
}
for(int i=xs.length()-1;i>=0;i--){
ans+=xs[i];
}
//溢出判断
if(ans.size()==10&&ans[0]!='-'&&ans>to_string(INT_MAX)){
return 0;
}
if(ans.size()==11&&ans[0]=='-'&&ans.substr(1)>to_string(INT_MAX)){
return 0;
}
return stoi(ans);
}
int main() {
// int a = reverse(123);
// int a = reverse(-123);
// int a = reverse(120);
int a = reverse(1534236469);
cout<<a;
return 0;
}
知识
负数取模后为负数
// int b = -12%10;
// cout<<b; //-2
整数取值范围
//-2,147,483,648 到 2,147,483,647