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?