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

 

 

posted @ 2018-06-24 16:01  eeeeeeee鹅  阅读(200)  评论(0编辑  收藏  举报