leetcode题解7- Reverse Integer(C++和python)

题目:

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.


解题思路:

    反转数字,注意考虑前面的空0和反转后数字是否越界。

代码C++版

    

class Solution {
public:
    int reverse(int x) {        
        string s  = to_string(x);
        std::reverse(s.begin(),s.end());  
        int flag = 1;
        if(x < 0) flag = -1;
        long reverseNum = 0;
        int s_size = (flag == 1)? s.size(): s.size()-1;   // 如果是负数,则字符串最后一位'-'不要计算进去
        for(int i = 0; i < s_size; i++){
            if(reverseNum == 0 && s[i] == '0') continue;  // 排除前面多余0
            reverseNum = reverseNum*10 + (s[i]-'0');
        }
        // 判断是否越界 正数2^31-1, 负数 -2^31
        if((reverseNum > std::pow(2,31)-1 && flag == 1)||(flag ==-1 && reverseNum > std::pow(2,31))) return 0; 
        return reverseNum*flag;       
        
    }
};


python 版

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        import math
        flag = False
        
        if x < 0:
            flag = True
        x = abs(x) 
        str_x = str(x)[::-1]
        if int(str_x) > 2147483648:
            return 0
        if flag:
            return -1*int(str_x)
        else:
            return int(str_x)


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014694994/article/details/79947147
文章标签: leetcode Reverse Integer
个人分类: Leetcode题解
上一篇leetcode题解1-Two Sum
下一篇leetcode题解20—Valid Parentheses
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭