7. Reverse Integer - jiejackyzhang/leetcode-note GitHub Wiki

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

这个题目的关键点在于如何处理integer溢出的问题。

public class Solution {
    public int reverse(int x) {
        int ans = 0;
        while(x != 0) {
            int tail = x % 10;
            int newAns = ans * 10 + tail;
            if((newAns - tail) / 10 != ans) {
                // integer overflow
                return 0;
            }
            ans = newAns;
            x = x / 10;
        }
        return ans;
    }
}
⚠️ **GitHub.com Fallback** ⚠️