Golang算法 - Leetcode

 主页   资讯   文章   代码   电子书 

7. Reverse Integer

Leetcode 链接

题目

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.

题意解析

对数字进行反转,如果反转后的数超出了 [MinInt32, MaxInt32] 的边界,则返回 0。

解决方案

用一个 int64 的数来存储反转后的 int32 数字,如果结果超出了 [MinInt32, MaxInt32],就返回 0。

Go 代码

func reverse(x int) int {
    var s int64

    for x != 0 {
        s = s*10 + int64(x)%10
        x /= 10
    }

    if s > math.MaxInt32 || s < math.MinInt32 {
        s = 0
    }

    return int(s)
}