problem:
Reverse digits of an integer.
example:
Example1: x = 123, return 321
Example2: x = -123, return -321
Difficulty:Easy
note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
hint1:
- a % b = a - (a / b) * b
- 判断是否越界
- 当x<0时,不能使用return -reverse(-x),INT_MIN=-INT_MAX-1,再调用函数时越界报错
code:
#include<stdio.h>
#include<limits.h>
int reverse(int x) {
int y = 0,temp;
while(x){
temp = x % 10; //获取x的奇数位
x = x / 10;
if(y > (INT_MAX / 10) || y < (INT_MIN / 10)){
return 0;
}
if((y == (INT_MAX / 10) || y == (INT_MIN / 10)) && temp >= 7){
return 0;
}
y = y * 10 + temp;
}
return y;
}
int main() {
int t = reverse(1534236469);
printf("%d\n",t);
}
hint2:
使用long型存放逆置的数字,再判断是否越界
int reverse(int x) {
long y = 0;
while(x){
y = y * 10 + x % 10;
x = x / 10;
printf("%d\n",y);
}
if(y > INT_MAX||y<INT_MIN){
return 0;
}
return y;
}
网友评论