7.反转整数

  1.  类静态变量需要在外部定义,且定义时不带static关键字;
  2. 对于数字常量默认为整型,如果表示范围大于整数的表示范围,会有编译告警,需要在后面加上U,例如,2147483648U,如果是long,需要加上UL,long long,则用LLU;
  3. 时间时间时间

#include <iostream>
#include <vector>
#include <math.h>

using namespace std;

class Solution {
public:
    const static unsigned int max_int;
    int reverse(int x) 
    {
        int sign  = (x >= 0) ? 1 : -1;
        unsigned int abs_x = (x > 0) ? x : -x;

        vector<unsigned int> v;
        unsigned int mod = abs_x % 10, left = abs_x / 10;
        v.push_back(mod);
        for (; 0 != left;)
        {
            mod = left % 10, left = left / 10;
            v.push_back(mod);
        }

        if (v.size() == 10 && v[0] > 2)   // exception 
        {
            return 0;
        }
        else                             // normal process
        {
            unsigned int result = 0, idx = 0;
            for (vector<unsigned int>::iterator it = v.begin(); it != v.end(); ++it, ++idx)
            {
                result += (*it) * myPow(10, v.size() - idx - 1);
            }

            if ((result > Solution::max_int) || (result == Solution::max_int && sign > 0)) // exception 
            {
                return 0;
            }
            else                    // normal process
            {
                return (int)result * sign;
            }
        }
    }

    int myPow(int x, int y)
    {
        int ret = 1;
        for ( ;y != 0; y--)
        {
            ret *= x;
        }

        return ret;
    }
};

const unsigned int Solution::max_int = 2147483648U;
int main()
{

    Solution sol;

    // example
    int result = sol.reverse(123);
    cout << result << endl;
    result = sol.reverse(-123);
    cout << result << endl;
    result = sol.reverse(120);
    cout << result << endl;

    // exception
    result = sol.reverse(0);
    cout << result << endl;
    result = sol.reverse(-1 * sol.myPow(2, 31));
    cout << result << endl;
    result = sol.reverse(-1 * sol.myPow(2, 31));
    cout << result << endl;

    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值