lintcode-413-反转整数

413-反转整数

将一个整数中的数字进行颠倒,当颠倒后的整数溢出时,返回 0 (标记为 32 位整数)。

样例

给定 x = 123,返回 321
给定 x = -123,返回 -321

标签

整数

思路

利用取余和除法取出整数每一位,需要注意整数越界问题

code

class Solution {
public:
    
    /*
     * @param n: the integer to be reversed
     * @return: the reversed integer
     */
    int reverseInteger(int n) {
        // write your code here
        bool isNeg = (n < 0);
        n = abs(n);
        long long res = 0;
        do {
            res *= 10;
            res += n % 10;
            n = n / 10;
        } 
        while (n > 0);
        if (res > INT_MAX) {
            res = 0;
        }
        if (isNeg == true) {
            return -1 * res;
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/libaoquan/p/7357080.html