目录
题目描述
给出一个32位的有符号整数,你需要将这个整数中每位上的数字反转。对于溢出32位的数字则返回0。
输入/输出描述
输入 | 321 |
输出 | 123 |
解决方案
题目较为简单,需要在两个地方注意:
- 输入的数字可能是负数。负数反转后还是负数
- 反转后的数字如果超出32位,则需要返回0
代码
package main
import "strconv"
func reverse(x int) int {
positive := true
if x < 0 {
positive = false
x = -x
}
xStr := strconv.Itoa(x)
resultStr := ""
for i := len(xStr) - 1; i >= 0; i-- {
resultStr += string(xStr[i])
}
result, _ := strconv.Atoi(resultStr)
if !positive {
result = -result
}
if result < -(1<<31) || result > (1<<31)-1 {
result = 0
}
return result
}
代码走读
package main
import "strconv"
func reverse(x int) int {
// 先判断x的正负性。记录后将x统一转换为正数(方便逆序)
positive := true
if x < 0 {
positive = false
x = -x
}
// 将x转换为字符串逆序,得到逆序后的字符串
xStr := strconv.Itoa(x)
resultStr := ""
for i := len(xStr) - 1; i >= 0; i-- {
resultStr += string(xStr[i])
}
// 根据先前记录的正负性,将逆序后的字符串还原为整数结果
result, _ := strconv.Atoi(resultStr)
if !positive {
result = -result
}
// 判断是否溢出32位
if result < -(1<<31) || result > (1<<31)-1 {
result = 0
}
return result
}