虽然是标注为简单的题目还是遇到不少坑的:
假设32 位的有符号整数,其中是一位是符号位,31位是代码位,所以能存储的数字范围是 [−2^31, 2^31 − 1]。所以过程中是可能出现超过int能存储的数字的,ans即结果要定义为long类型而非int类型的。
queue.poll()返回的是object的类型,要通过long(queue.poll())强制转型。
long转化为int输出是强制转换即int(ans*tag)会报错,最后是通过new Long(ans*tag).intValue()转换通过的,附上解决过程中参考的链接:https://blog.csdn.net/qq_38245537/article/details/78284843
为什么int的存储范围是[−2^31, 2^31 − 1],找到一个比较好的解释:https://blog.csdn.net/Ocean_tu/article/details/82660308
用了队列的先进先出特点。
java代码实现如下:
class Solution {
public int reverse(int x) {
Queue<Integer> queue = new LinkedList<Integer>();
int tag;
if(x<10&&x>-10) return x;
if(x>0) tag=1;
else tag=-1;
x=Math.abs(x);
int tmp=0;
while(x>0){
queue.offer(x%10);
x=x/10;
tmp++;
}
long ans=0l;
while(tmp>0){
ans=ans+(long)queue.poll()*(int)Math.pow(10*1.0,(tmp-1)*1.0);
tmp--;
}
if(ans*tag>Math.pow(2,31)-1||ans*tag<(-1)*Math.pow(2,31)) return 0;
return new Long(ans*tag).intValue();
}
}