美文网首页
LeetCode 7. Reverse Integer

LeetCode 7. Reverse Integer

作者: 洛丽塔的云裳 | 来源:发表于2020-03-31 13:36 被阅读0次

0. 题目

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: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

1. C++版本

V0版本:第一种解法是将数字转化为string,然后将其反转,注意"0"这种特殊情况,注意越界!!运行时间4 ms

    int reverse(int x) {
        string s = std::to_string(x);
        char tmp;
        int start_pos = x<0 ? 1 : 0;
        int end_pos = s.size()-1;
        while (end_pos >=0 && s[end_pos] == '0') end_pos--;
        // 注意考虑"0"的情况
        if (end_pos < 0)
            return 0;
        s = s.substr(0, end_pos+1);
        while (start_pos < end_pos) {
            tmp = s[start_pos];
            s[start_pos] = s[end_pos];
            s[end_pos] = tmp;
            start_pos++; end_pos--;
        }
        if (std::stod(s) > INT_MAX || std::stod(s) < INT_MIN)
            return 0;
        return std::stoi(s);
    }

V1版本:使用数学方法。 运行0 ms

    int reverse(int x) {
        double result = 0;
        while (x) {
            result = result * 10 + x % 10;
            x = x / 10;
        }
        return (result > INT_MAX || result < INT_MIN) ? 0 : result;
    }

2. Python版本

思想先转化为字符串,先反转,然后去除连续的"0"

    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        start_pos = 1  if x < 0  else 0
        s = str(x)
        if float(s) > 2147483648 or float(s) < -2147483647:
            return 0
        if start_pos == 1:
            s = s[:start_pos-1:-1]
        else:
            s = s[::-1]
        num = 0
        while num < len(s) and s[num] == '0':
            num += 1
        if num != len(s):
            s = s[num:]
        s = '-' + s if start_pos == 1 else s
        if float(s) > 2147483648 or float(s) < -2147483647:
            return 0
        return int(s)

相关文章

网友评论

      本文标题:LeetCode 7. Reverse Integer

      本文链接:https://www.haomeiwen.com/subject/oekduhtx.html