LeetCode No.7 [Reverse Integer]

Description

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.

Leet Code Link


基于数学算法的实现

使用取余的方法从低位取得数字, 再通过*10的方式实现数字的排列反转。

1
2
3
4
5
6
7
8
9
10
11
12
13
func reverse(x int) int {
var result int
for x != 0 {
result = result*10 + x%10
x = x / 10
}
if result > math.MaxInt32 || result < math.MinInt32 {
return 0
}
return result
}

基于字符串的实现

将数字转换为字符串, 并通过字符串数组前后的值调换来实现。这里还需要注意负号的处理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
func reverseString(str string) string {
bytes := []byte(str)
for i, j := 0, len(bytes)-1; i < j; i, j = i+1, j-1 {
bytes[i], bytes[j] = bytes[j], bytes[i]
}
return string(bytes)
}
func reverse(x int) int {
str := strconv.Itoa(x)
result := 0
if str[0] == '-' {
result, _ = strconv.Atoi(reverseString(str[1:]))
result = -result
} else {
result, _ = strconv.Atoi(reverseString(str))
}
if result > math.MaxInt32 || result < math.MinInt32 {
return 0
}
return result
}