题目:
给定32位有符号整数,翻转整数的数字。例:123—>321(溢出则返回0)
我的答案:
int reverse(int x) {
int a[10], b[11];
int i,j,flag = 0;
long long out = 0;
b[0] = abs(x);
for (i = 0; i < 10; i++)
{
a[i] = b[i] / (pow(10,(9 -i )));
b[i + 1] = b[i] % (int)(pow(10,(9 - i)));
if (a[i] > 0 && flag == 0)
{
j = i;
flag = 1;
}
}
for (i = j; i < 10; i++)
{
out += a[i] * (pow(10,i-j));
}
if (x < 0)
out = -out;
if (out >= (pow(2,31)) || out < (pow(-2,31)))
out = 0;
return out;
}
错误历史:
- 运行出错:
C语言没有幂次,只能用pow()函数,且pow()函数使用且返回double类型 - 第一次提交:
out += a[i] * (pow(10,i-j)); 语句没有考虑到位,逻辑没有缕通顺 - 第二次提交:
溢出问题。out溢出后才进行判断。 - 第三次提交:
成功
其余需要注意的地方
Long和int都为32位,long long为64位
答案:
class Solution {
public:
int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > INT_MAX/10 || (rev == INT_MAX / 10 && pop > 7)) return 0;
if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
};