7_Reverse Integer

没有想出来, 仿照(或者照搬?)http://www.cnblogs.com/grandyang/p/4125588.html来写

注意点:
反转溢出问题, 解决方法: 使用比该数字范围大的类型定义返回值

class Solution {
public:
    int reverse(int x) {
        long long int ret = 0;
        
        while(0 != x) {
            ret = ret*10 + x%10;
            x /= 10;
        }
        
        //return (ret > INT_MIN || ret < INT_MAX)? ret : 0;
         return (ret < INT_MIN || ret > INT_MAX) ? 0 : ret;
    }
};

半个自己写的, 考虑符号, 虽然多余了

class Solution {
public:
    int reverse(int x) {
        long long ret = 0;
        // int positive = 1;
        long long positive = 1;

        if (x < 0) {
            positive = -1;
            x *= positive;
        }

        while (x != 0) {
            ret = ret * 10 + x % 10;
            x /= 10;
        }
        
        ret *= positive;
        
        return (ret < INT_MIN || ret > INT_MAX) ? 0 : ret;
    }
};
上一篇:LeetCode-41-First Missing Positive


下一篇:20.unittest使用