my-solutions/leetcode/0007-reverse-integer/main.go

31 lines
470 B
Go
Raw Permalink Normal View History

2023-11-30 11:56:47 +05:00
package main
import (
"math"
)
func reverse(x int) int {
var res int32
var mul int32 = 1
if x < 0 {
mul = -1
x *= -1
}
for x != 0 {
digit := mul * int32(x % 10)
if mul > 0 && (math.MaxInt32 - digit) / 10 < res {
return 0
}
if mul < 0 && (math.MinInt32 - digit) / 10 > res {
return 0
}
res = res * 10 + digit
x /= 10
}
return int(res)
}