【两次过】Lintcode 413:反转整数

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

样例

给定 x = 123,返回 321

给定 x = -123,返回 -321

解题思路:

    一开始想的是用stack数据结构来暂存分离的数字,然后再依次pop组成反转数字,这样实现太复杂了需要考虑正负两种情况,其实这里无需借助数据结构,直接可以颠倒。

    写出自己臭长的代码,后来发现网上大神的代码几行就写完了!佩服。思路差不多,代码更简洁。

    注意一个点:负数的余数和除数都为负数,利用这点可以不用分类讨论!

class Solution {
public:
    /**
     * @param n: the integer to be reversed
     * @return: the reversed integer
     */
    int reverseInteger(int n) 
    {
        // write your code here
        long long res = 0; //不断求余和乘以十,注意溢出  
        while (n) 
        {  
            res = 10 * res + n % 10;  
            n /= 10;  
        }  
        //使用long来保存可能溢出的结果,再与最大/最小整数相比较  
        return (res < INT_MIN || res > INT_MAX) ? 0 : res;
    }
};


猜你喜欢

转载自blog.csdn.net/majichen95/article/details/80698639
今日推荐