Reverse Integer

Description

Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

将输入的十进制数倒序输出

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
func reverse(x int) int {
    r := 0

    for x != 0 {
        r *= 10
        r += x % 10
        x /= 10
    }

    if -math.MaxInt32 < r && r < math.MaxInt32 {
        return r
    }

    return 0
}