Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
思路:
1、将整数转化成字符数组;
2、对字符数组进行反转操作;
3、拼接字符数组中的元素,进行返回即可
package main
import (
"fmt"
"math"
"strconv"
)
func main() {
intput := 123
ret := reverse(intput)
fmt.Println(ret)
}
func reverse(x int) int {
MIN_INT := math.MinInt32
MAX_INT := math.MaxInt32
if (x < MIN_INT || x > MAX_INT){
return 0
}
if ((x > -9) && (x < 9)){
return x
}
isNegative := false
if (x <0){
x = (-1) * x
isNegative = true
}
stringTem := strconv.Itoa(x)
stringArrs := []byte(stringTem)
for beg, end := 0, len(stringArrs) - 1; beg < end; beg, end = beg + 1, end - 1{
tem := stringArrs[beg]
stringArrs[beg] = stringArrs[end]
stringArrs[end] = tem
}
retBeg := 0
for {
if stringArrs[retBeg] == '0' {
retBeg++
} else {
break
}
}
stringRet := string(stringArrs[retBeg:])
if isNegative == true {
stringRet = "-" +stringRet
}
temRet,_ := strconv.ParseInt(stringRet,10,64)
if (temRet < int64(MIN_INT) || temRet > int64(MAX_INT)){
return 0
}
return int(temRet)
}