You've successfully subscribed to The Daily Awesome
Great! Next, complete checkout for full access to The Daily Awesome
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

007. 整数反转 - Reverse Integer

. 1 min read

007. 整数反转 - Reverse Integer

【栈】 【纯数学】

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

注意:

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

Example:

示例 1:

输入: 123
输出: 321

示例 2:

输入: -123
输出: -321

示例 3:

输入: 120
输出: 21

Solution

Solution 【栈】【转字符串操作】 ( 33ms)

class Solution {
    public int reverse(int x) {
		long result = 0;
		String str = String.valueOf(x);
		Stack<Character> stack = new Stack<>();
		for (int i = 0; i < str.length(); i++)
			stack.push(str.charAt(i));
		str = "";
		while (stack.size() > 1)
			str += stack.pop();
		if (stack.peek() != '-') {
			str += stack.pop();
			result = Long.parseLong(str);
		} else
			result = -Long.parseLong(str);
		
		return x;
	}
}

Solution 【纯数学】 ( 15ms)

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

Solution 【纯数学】 ( 12ms)

int reverse(int x) {
    if (x == 0) return 0;

    int abs = x > 0 ? x : -x;  // 取绝对值
    int digit;
    long ans = 0;
    int max = 0X7FFFFFFF, min = 0X80000000;  // 补码 (2^31-1=2147483647,-2^31=-2147483648)
    
    while (abs > 0) {  // 反转
        digit = abs % 10;  // 取个位
        ans = ans * 10 + digit; 
        abs /= 10;
    }

    if (x < 0) ans = -ans;  // 原值为负
    if (x > 0) {  // 溢出判断
        if (ans > max) return 0;
    } else {
        if (ans < min) return 0;
    }
    
    return ans;  // 返回值从long转为int
}

Notes

转字符串操作需要考虑避免越界