难点:如何判断翻转之后是否超出了int类型的范围
解决办法
(1) 使用long int 类型 扩大范围进行判断,最后进行强制类型转换返回int类型
(2) 将范围的各位数 存储在vector数组中注意比较。不好,消耗内存的同时需要额外的循环比较判断。(做题时采用了该方法,结果并不理想)
int reverse(int x){
int c = 1.0;
if (x < 0){
c = -1.0;
}
int result = 0;
vector<int> remains; //余数部分
int max[10] = {2,1,4,7,4,8,3,6,4,8};
int min[10] = {2,1,4,7,4,8,3,6,4,7};
int k = 0;
int remain;
while(x != 0){
remain = x % 10 * c;
remains.push_back(remain);
x = x / 10;
if (k > 10)
return result;
++k;
}
if (k == 10){
if (c == -1.0){
for (int i = 0; i < 10;++i){
if (remains[i] < min[i])
break;
else if (remains[i] == min[i])
continue;
else
return 0;
}
}
else
for (int i = 0; i < 10; ++i){
if (remains[i] < max[i])
break;
else if (remains[i] == max[i])
continue;
else
return 0;
}
}
int step = pow(10,remains.size() - 1);
for (vector<int>::iterator it = remains.begin();it != remains.end();++it){
result = result + *it * step;
step /= 10;
}
return result * c ;
}