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
- 判斷是否越界
- 當(dāng)x<0時(shí)统捶,不能使用return -reverse(-x)斧散,INT_MIN=-INT_MAX-1雷逆,再調(diào)用函數(shù)時(shí)越界報(bào)錯(cuò)
code:
#include<stdio.h>
#include<limits.h>
int reverse(int x) {
int y = 0,temp;
while(x){
temp = x % 10; //獲取x的奇數(shù)位
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型存放逆置的數(shù)字,再判斷是否越界
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;
}