Reverse Integer *Reverse digits of an integer.
Example1: x = 123, return 321 Example2: x = -123, return -321
click to show spoilers.
Note: The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
Subscribe to see which companies asked this question.*
解题过程 : 如果输入的是负数,我们先将他化为正数,最后再加上负号,将整数每个位置上的值都按顺序添加到一个数组中,然后用数组将他倒转,要保证倒转后的值不溢出,加一个判断溢出的条件就可以了,代码如下:
int reverse(int x) { int s[32]; int i = 0; int flag = 0; if(x<0){ x = -x; flag = 1; } while(x>0){ s[i] = x % 10; x = (x - s[i]) / 10; i++; } long long y = 0; for(int j=0; j<i; j++ ){ y = s[j] * pow(10,i-j-1) + y; } if(y>2147483648 ){ return 0;} if(flag == 0) return y; else return -y; }