給你一個(gè) 32 位的有符號(hào)整數(shù) x 坎拐,返回將 x 中的數(shù)字部分反轉(zhuǎn)后的結(jié)果硼莽。
如果反轉(zhuǎn)后整數(shù)超過(guò) 32 位的有符號(hào)整數(shù)的范圍 [?231, 231 ? 1] 侯勉,就返回 0猜极。
假設(shè)環(huán)境不允許存儲(chǔ) 64 位整數(shù)(有符號(hào)或無(wú)符號(hào))缨叫。
來(lái)源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/reverse-integer
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有延届。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán)剪勿,非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
此題要注意三點(diǎn):
- 負(fù)數(shù)
- 末尾數(shù)為 0 的例如 100方庭,反轉(zhuǎn)之后不是 001厕吉,要把前面的 0 去掉
- 注意判斷數(shù)值是否超出范圍
代碼如下:
func reverse(x int) int {
if x > math.MaxInt32 || x < math.MinInt32 {
return 0
}
if x == 0 {
return 0
}
isNegative := false
if x < 0 {
isNegative = true
x = x * -1
}
builder := make([]int, 0)
for x != 0 {
t := x % 10
x = x / 10
if len(builder) == 0 && t == 0 {
continue
}
builder = append(builder, t)
}
fmt.Println(builder)
t := int64(0)
weight := 1
// 倒序遍歷
i := len(builder) - 1
for i >= 0 {
item := builder[i]
t += int64(item * weight)
weight *= 10
i -= 1
}
if isNegative {
t = t * -1
}
if t > math.MaxInt32 || t < math.MinInt32 {
return 0
}
return int(t)
}