413 反转整数

原题网址:https://www.lintcode.com/problem/reverse-integer/description

描述

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

您在真实的面试中是否遇到过这个题?  是

样例

给定 x = 123,返回 321

给定 x = -123,返回 -321

标签
整数
 
思路:按位依次取出数字存入数组,再将数字取出乘以对应的权值完成反转。注意反转过程中随时判断数值是否超出int型范围,超出范围则返回0。
 
AC代码:
class Solution {
public:
    /**
     * @param n: the integer to be reversed
     * @return: the reversed integer
     */
    int reverseInteger(int n) {
        // write your code here

int m=n,result=0; vector<int> tmp; while(m) { tmp.push_back(m%10); m=m/10; } int size=tmp.size(); for (int i=0;i<size;i++) { result=result+tmp[i]*pow(10.0,size-1-i); if (result>=INT_MAX||result<=INT_MIN) { return 0; } } return result; } };

 

其他思路:

https://blog.csdn.net/zsjmfy/article/details/53405494

https://www.cnblogs.com/grandyang/p/5778281.html   代码精简。第二个代码,如果发生越界,那么得到的值t/10后肯定不会等于res。【因为数据越界后截断,而10不是2的幂】

https://blog.csdn.net/qq_23225317/article/details/53641864

 

 

转载于:https://www.cnblogs.com/Tang-tangt/p/9220772.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值