Given a 32-bit signed integer, reverse digits of an integer.
给定32位有符号整数,整数的反向数字。
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.
代码:
#include <stdio.h>
#include <stdlib.h>
int reverse(int x)
{
long int tmp = x;
long int value = 0;
int res = -1;
while( 0 != res ) // 实现数据反向
{
res = x/10;
value*=10;
value+=x%10;
x/=10;
}
if(value > 0xffffffff || (((int)tmp > 0) && ((int)value < 0)) || ((int)tmp < 0) && ((int)value > 0)) // 判断数据合法性
return 0;
return (int)value;
}
int main(int argc,char **argv)
{
int handle = 0;
if(NULL == argv[1])
handle=0;
else
handle=atoi(argv[1]);
printf("handle = %d, reverse = %d.\n", handle, reverse(handle));
return 0;
}