ReverseInteger


//Given a 32-bit signed integer, reverse digits of an integer.

public class ReverseInteger {
    public int reverse(int x) {
        //if( x < Math.pow(-2,31) || x > Math.pow(2,31)-1 ) return 0;
        if (x > 214748364 || x < -2143847412) return 0;
        int result = 0;
        boolean isPositiveNum = true;
        if (x < 0){
            x = Math.abs(x);
            isPositiveNum = false;
        }
        int length = caculateNumLength(x);
        while (x != 0){
            if (Math.pow(10,length-1) > Integer.MAX_VALUE) return 0;
            result += Math.pow(10,length-1)*(x%10);
            x = x/10;
            length--;
        }
        if (!isPositiveNum) return -result;
        return result;
    }

    private int caculateNumLength(int x){
        int num = x;
        int count = 0;
        while (num > 0){
            num = num/10;
            count++;
        }
        return count;
    }

    public static void main(String[] args) {
        ReverseInteger ri = new ReverseInteger();
        System.out.println(ri.reverse(-2147483412));
    }
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页