Reverse Integer
程序员文章站
2024-03-22 14:04:52
...
两种解法 leetcode通过时间一致
func reverse(x int) int {
flag := false
if x<0{
flag = true
x = -x
}
numSlice := []rune(strconv.Itoa(x))
var numResSlice []rune
for i:=len(numSlice)-1;i>=0;i--{
numResSlice = append(numResSlice,numSlice[i])
}
final,_ := strconv.Atoi(string(numResSlice))
if flag{
final = -final
}
if final>2147483648 || final< -2147483648{
return 0
}
return final
}
func reverse(x int) int {
var res []int
var final int
remainder := 0
for i:=10;;i=i*10{
remainderTmp := x%i
res = append(res,(remainderTmp - remainder)/(i/10))
remainder = remainderTmp
if remainderTmp == x{
break
}
}
a := 1
for i:=len(res)-1;i>=0;i--{
final = final+res[i]*a
a = a*10
}
if final>2147483648 || final< -2147483648{
return 0
}
return final
}
下一篇: 笛卡尔树