用 Golang 实现,给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
输入: 123 输出: 321
输入: -123 输出: -321
输入: 120 输出: 21
package main
import (
"fmt"
"math"
"strconv"
)
func reverse(x int) int {
var nums, newnums int
for x != 0 {
a := x % 10
newnums = nums * 10 + a
nums = newnums
x = x / 10
if nums > math.MaxInt32 || nums < math.MinInt32 {
return 0
}
}
return nums
}
func reverse2(x int) int {
if judge(x) == 0 {
return 0
}
if x >= 0 {
temp := ReverseString(strconv.Itoa(x))
res, _:=strconv.Atoi(temp)
return judge(res)
} else {
temp := ReverseString(strconv.Itoa(-x))
res, _:=strconv.Atoi(temp)
return judge(-res)
}
}
func ReverseString(s string) string {
runes := []rune(s)
for from, to := 0, len(runes)-1; from < to; from, to = from+1, to-1 {
runes[from], runes[to] = runes[to], runes[from]
}
return string(runes)
}
func judge(x int) int {
if x > math.MaxInt32 || x < math.MinInt32 {
return 0
} else {
return x
}
}
func main() {
fmt.Println("嗨客网(www.haicoder.net)")
fmt.Println(reverse(123))
fmt.Println(reverse(-123))
fmt.Println(reverse(120))
}
程序运行后,控制台输出如下:
我们使用了两种方式实现了反转。