leetcode 翻转数字

翻转数字,很有意思的一道题。
题目如下:
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.

可以看到,题目要求如果翻转之后数字超过32位int范围 需要返回0
记得int型的范围是[-2^31,2^31-1],因此Integer.MIN_VALUE如果去掉符号,是超出了范围的。
写代码的时候要单独注意一下这个细节。
java中常用的取绝对值函数Math.abs(int),如果结果超出int范围,则会返回原始数值,不会进行取绝对值操作。

我的代码如下:
public class Solution {
    public int reverse(int x){
        int flag=0;
        if(x==-2147483648){
            return 0;
        }
        if(x<0){
            x=-x;
            flag=1;
        }
        String temp1=x+"";
        double temp2=0.0;
        String temp3="";
        Stack stack=new Stack<>();
        char[] charArray=temp1.toCharArray();
        for(int i=0;iInteger.MAX_VALUE||temp2


你可能感兴趣的:(心得,java,算法)