标签:type ddc post eve pre code 注意 func tracking
//假设有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);
}
标签:type ddc post eve pre code 注意 func tracking
原文地址:http://www.cnblogs.com/liguangsunls/p/7071603.html