leetcode 7. Reverse Integer【大整数】

题目

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值