首页 > 代码库 > [Leetcode]-Reverse Integer
[Leetcode]-Reverse Integer
//假设有pow函数,Linux下编译一定要加-lm
//gcc ReverseInteger.c -o ReverseInteger -lm
关键:一定要注意操作过程中int类型超界
有可能输入数据没有超界。可是反向逆序后,甚至在逆序操作过程中都有可能超界。反正时刻检查超界与否
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <limits.h>
int reverse(int x) {
int f = 0;
int k = 0;
int m = 0;
int tem=0;
int r = 0;
int INT_MAX_DIV10 = INT_MAX / 10;
if(x<-INT_MAX && x >INT_MAX)
return 0;
if(x < 0)
{
x = -x;
f = 1;
}
while(x)
{
if(r > INT_MAX_DIV10) return 0;
r = r*10;
tem = x % 10;
if(INT_MAX - tem < r) return 0;
r = r + tem;
x = x/10;
}
if(f)
r = -r;
return r;
}
int main()
{
int x = 1;
int r = reverse(x);
printf("reverse x %d = %d \n",x,r);
x = 13579;
r = reverse(x);
printf("reverse x %d = %d \n",x,r);
x = 0;
r = reverse(x);
printf("reverse x %d = %d \n",x,r);
x = -13579;
r = reverse(x);
printf("reverse x %d = %d \n",x,r);
x = -1;
r = reverse(x);
printf("reverse x %d = %d \n",x,r);
x = 1534236469; //原数不超界。逆序超界
r = reverse(x);
printf("reverse x %d = %d \n",x,r);
}
[Leetcode]-Reverse Integer
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。