3 Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

 Input: 123
 Output: 321

Example 2:

 Input: -123
 Output: -321

Example 3:

 Input: 120
 Output: 21

Note:

Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

第一次写的代码相当丑陋,速度上只超越了19%的提交算法,使用内存上更可怜(我就不贴了),虽然如此,还是把第一次的代码贴在下面:

class Solution {
public:
    
    int sign(int x)
    {
        if(x>0) return 1;
        if(x<0) return -1;
        else return 0;
    }
    
    
    int reverse(int x) {
        
        vector<int> integer;
        int temp = x;
        

        do{
            
            int curr_pos = temp%10;
            temp = temp/10;
            
            integer.push_back(curr_pos);
                
        }while(temp != 0);
        
        int inverse = 0;
        int len = integer.size();
        
        for(int i=0;i<len;i++)
        {
            inverse += integer[i] * pow(10,len-i-1);
        }
        
        if(sign(inverse)*sign(x) < 0) return 0;
        if(inverse == -2147483648 ) return 0;
           
        return inverse;
        
      
    }
};

后来去观摩了一下大神们的写法, 果然很简洁,真不知道自己之前瞎写了些啥:)
大神们的写法就省掉了我的那个既费空间又费时间的vector,而且边界检查比我写的规范多了(现在简直不忍直视我的第一次代码)。第二次代码迭代如下:

class Solution {
public:
    int reverse(int x) {
     
        int ans = 0;
        while(x)
        {
            if(ans > INT_MAX/10 || ans < INT_MIN/10) return 0;
            else{
               ans = (ans*10) + x%10;
               x = x/10;  
            }
        } 
        return ans;
    }
};
posted @ 2019-07-09 05:57  孙小鸟  阅读(129)  评论(0编辑  收藏  举报