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

逆置数字

时间:2015-08-26 11:57:31      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

我已开始的策略其实是直接转字符串操作一下完了:

int reverse(int x) {
    if (x == 0){
        return 0;
    }
    while (x % 10 == 0){
        x /= 10;
    }
    auto&& s = to_string(x);
    auto result = atoll(string(s.crbegin(), s.crend()).data());
    if (result > INT32_MAX){
        return 0;
    }
    return static_cast<int>(x < 0? -result : result);
}

但是这效率低啊,于是联想到上一个判断回文数的问题,我就改成了:

int reverse(int x) {
    long long result = 0;
    while (x != 0){
        result = result * 10 + x % 10;
        x /= 10;
    }
    if (result > INT32_MAX || result < INT32_MIN){
        return 0;
    }
    
    return static_cast<int>(result);
}

 

逆置数字

标签:

原文地址:http://www.cnblogs.com/wuOverflow/p/4759903.html

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