table of Contents
Title description
Given a 32-bit signed integer, you need to invert the digits on each bit of the integer. For overflowing 32-bit numbers, 0 is returned.
Input/output description
enter | 321 |
Output | 123 |
solution
The topic is relatively simple, and you need to pay attention to two places:
- The number entered may be negative. Negative number is still negative after reversal
- If the inverted number exceeds 32 bits, it needs to return 0
Code
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
}
Code walkthrough
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
}