天天看点

LeetCode之Reverse Integer

1、题目

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.

2、代码实现

代码实现1、

通过不了LeetCode

public static int reverse(int x) {
        if (x > Integer.MAX_VALUE || x < Integer.MIN_VALUE) {
            return 0;
        }
        boolean flag = false; //x是负数就是true,正数false
        if (x < 0) {
            flag = true;
        }
        String string = String.valueOf(x);
        String spliteStr =  flag ? string.substring(1) : string;
        StringBuffer sb = new StringBuffer(spliteStr);
        sb = sb.reverse();
        String result = sb.toString();
        result = flag ? "-" + result : result;
        long value = Long.valueOf(result);
        if (value > Integer.MAX_VALUE || value < Integer.MIN_VALUE) {
            return 0;
        }
        return (int)value;
    }      

代码实现二、

public static int reverse1(int x) {
        if (x > Integer.MAX_VALUE || x < Integer.MIN_VALUE) {
            return 0;
        }
        long result = 0;
        int temp = Math.abs(x);
        while (temp > 0) {  
            result *= 10;
            result = result + temp % 10;
            temp /= 10;
        }
        
         if (result > Integer.MAX_VALUE ||result<Integer.MIN_VALUE ) {
            return 0;
        }
        return (int)(x >= 0 ? result : -result);
    }      

代码实现三

可以通过LeetCode

public static int reverse3(int n) {
        if (n > Integer.MAX_VALUE || n < Integer.MIN_VALUE) {
            return 0;
        }
        //输出结果定义为long
        long sum=0;
        while (n != 0) {
            int s = n % 10;
            sum = sum * 10 + s;
            n = n / 10;
        }
        //防止溢出操作
        if (sum > Integer.MAX_VALUE || sum < Integer.MIN_VALUE) {
            return 0;
        }
        return (int)sum;
    }      

注意有溢出问题,对比分析,第一个实现和第二个实现 不越界没问题。

继续阅读