Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode-7. Reverse Integer #14

Closed
ninehills opened this issue Jul 17, 2017 · 0 comments
Closed

LeetCode-7. Reverse Integer #14

ninehills opened this issue Jul 17, 2017 · 0 comments
Labels

Comments

@ninehills
Copy link
Owner

ninehills commented Jul 17, 2017

20170718

问题

https://leetcode.com/problems/reverse-integer/

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

思路

  • 一种想法是转换为字符串后反序
  • 还有一种办法就是每次将x除以十取模后,在乘起来
  • 至于overflow的判断,可以定义x为64bit整数,然后判断即可

解答

class Solution():
    def reverse(self, x):
        """第一种想法直接用库函数
        :type x: int
        :rtype: int
        """
        if x >= 0:
            ret = int(str(x)[::-1])
        else:
            ret = -1 * int(str(x)[:0:-1])
        if ret >= -1*2**31 and ret <= 2**31 - 1:
            return ret
        else:
            return 0

# -321
print(Solution().reverse(-10))

由于Python的%的实现方式是 -1 % 10 = 9,而不是 -1 % 10 = -1,我们取一个golang的例子

package main

import "fmt"

// ----------------------

func reverse(x int) int {
        var r int64 = 0
        var xx int64 = int64(x)
        for xx != 0 {
                r = r*10 + xx%10
                xx = xx / 10
        }
        const MaxInt = int32(^uint32(0) >> 1)
        const MinInt = -MaxInt - 1
        if r > int64(MaxInt) || r < int64(MinInt) {
                return 0
        } else {
                return int(r)

        }
}

// ----------------------

func main() {
        fmt.Println(reverse(123))
        fmt.Println(reverse(-234))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant