LeetCode2:整数反转

集思广益
题意描述:
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

示例:

示例 1:
输入: 123
输出: 321

示例 2:
输入: -123
输出: -321

示例 3:
输入: 120
输出: 21

解法1:

class Solution {
    public int reverse(int x) {
        String a = Integer.toString(x);
        int b = 1;
        if(a.charAt(0) == '-'){
            a = a.substring(1);
            b = -1;
        }
        char[] char1 = a.toCharArray();
        char[] result = new char[char1.length];
        for(int i = char1.length - 1; i >= 0; i--){
            result[char1.length - 1- i ] = char1[i];
        }
        //判断有没有溢出
        Long value = Long.valueOf(new String(result));
        if(value > Integer.MAX_VALUE || value < Integer.MIN_VALUE){
            return 0;
        }
        return (int) (value * b);
        
    }
}

解法2:

class Solution {
    public int reverse(int x) {
        int a;
        long b = 0;
        while(x != 0){
            a = x % 10;
            x = x / 10;
            b = b * 10 + a;
        }
        if(b > Integer.MAX_VALUE || b < Integer.MIN_VALUE){
            return 0;
        }
        return (int) b;
    }
}

解法3:
真牛逼。。

class Solution {
    public int reverse(int x) {
        long a = 0;
        while(x != 0){
            a = a * 10 + x % 10;
            x /= 10;
        }
        return (a < Integer.MIN_VALUE || a > Integer.MAX_VALUE) ? 0:(int) a;
    }
}
发布了26 篇原创文章 · 获赞 4 · 访问量 4454
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章