【面试题】反转整数

polaris · · 4525 次点击
```go func Reverse(x int32) int32 { var xx, rx, tnum, pos, negative int32 //备份原值 xx = x var posNum, posStart, maxLan int //int32最大长度 maxLan = 11 //判断是否负数 negative = 1 if x < 0 { negative = -1 xx = xx * -1 } for i := maxLan; i >= 0; i-- { tnum = int32(math.Pow10(i)) if xx >= tnum { pos = xx / tnum if pos > 0 || posStart > 0 { if posStart == 0 { posStart = 1 } fmt.Println(i, pos) posNum++ rx += pos * (int32(math.Pow10(posNum - 1))) } xx = xx - pos*tnum } } rx = rx * negative return rx } ```
#1
更多评论
polaris
社区,需要你我一同完善!
你这写的有点复杂了,而且还有 bug:`Reverse(10010)` 结果是 11,明显不对!
#2
有个简单粗暴的实现方法 package main import ( "log" "strconv" ) func reverseInt(param int) int64 { var dataToReturn int64 // 把被反转的参数转为字符串并填充到runes切片中 runes := []rune(strconv.FormatInt(int64(param), 10)) // 把runes切片的内容颠倒顺序 for start, end := 0, len(runes)-1; start < end; start, end = start+1, end-1 { runes[start], runes[end] = runes[end], runes[start] } // 把字符串转为整数,负数特别对待 if param < 0 { dataToReturn, _ = strconv.ParseInt(string(runes[:len(runes)-1]), 10, 64) dataToReturn = dataToReturn * int64(-1) } else { dataToReturn, _ = strconv.ParseInt(string(runes), 10, 64) } return dataToReturn } func main() { log.Println(reverseInt(-10010)) } ![捕获.PNG](https://static.studygolang.com/171007/110439a8a710f85ab1fd7e36632dede3.PNG)
#3