码迷,mamicode.com
首页 > 其他好文 > 详细

[LintCode] Reverse Integer 翻转整数

时间:2016-08-17 01:22:13      阅读:386      评论:0      收藏:0      [点我收藏+]

标签:

 

Reverse digits of an integer. Returns 0 when the reversed integer overflows (signed 32-bit integer).

 
Example

Given x = 123, return 321

Given x = -123, return -321

 

LeetCode上的原题,请参见我之前的博客Reverse Integer

 

解法一:

class Solution {
public:
    /**
     * @param n the integer to be reversed
     * @return the reversed integer
     */
    int reverseInteger(int n) {
        long long res = 0;
        while (n != 0) {
            res = 10 * res + n % 10;
            n /= 10;
        }
        return (res < INT_MIN || res > INT_MAX) ? 0 : res;
    }
};

 

解法二:

class Solution {
public:
    /**
     * @param n the integer to be reversed
     * @return the reversed integer
     */
    int reverseInteger(int n) {
        int res = 0;
        while (n != 0) {
            int t = res * 10 + n % 10;
            if (t / 10 != res) return 0;
            res = t;
            n /= 10;
        }
        return res;
    }
};

 

[LintCode] Reverse Integer 翻转整数

标签:

原文地址:http://www.cnblogs.com/grandyang/p/5778281.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!