题目:
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
题解:
因为还不太会用c++和java,所以用c语言写的,题意很好理解,题也很简单,但需要注意溢出的问题,输入没有溢出,但翻转可能有溢出。
代码:
int reverse(int x) {
long long y=0; //用longlong为了看是否有溢出
if(x>=pow(2,31)-1||x<=-pow(2,31)) return 0;
while(x!=0)
{
int v=x%10;
y=y*10+v;
if(y>pow(2,31)-1||y<-pow(2,31)) return 0;
x/=10;
}
int n=y;
return n;
}