[Leetcode]-Reverse Integer
阿新 • • 發佈:2017-06-23
keyword () text ++ ext leetcode fad clas 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);
}
[Leetcode]-Reverse Integer