7.M 整数反转
Problem: 7. 整数反转
思路
x
不断mod 10
取余数,取出最后一位。ans
不断* 10
,然后加上x
的余数。需要特别注意res
是否超出范围
Code
import "math"
func reverse(x int) int {
res := 0
for x != 0 {
if res < math.MinInt32/10 || res > math.MaxInt32/10 {
return 0
}
res = res*10 + x%10
x /= 10
}
return res
}
Last updated
Was this helpful?