
Reserve int
把一串數字反轉過來, 但是如果反轉後數字大於小於 [-231, 231 – 1]這個範圍, 則回傳0
解題脈絡
把數字轉換為 []byte , 接下來用反轉string 的方式進行, 回傳時判斷數字是否超出限制範圍
寫法
func reverse(x int) int {
nega := false
if x < 0 {
nega = true
x = x * -1
}
str := strconv.Itoa(x)
bytes := []byte(str)
i := 0
j := len(str) - 1
for i < j {
bytes[i], bytes[j] = bytes[j], bytes[i]
i++
j--
}
str = string(bytes)
if nega {
str = fmt.Sprintf("-%s", str)
}
res, _ := strconv.Atoi(str)
if res > (1<<31) || res < -(1<<31) {
return 0
}
return res
}
解法千變萬化, 我的太複雜了, 可以再想想除了這種解法, 還有什麼方式