【面试题】反转整数

polaris · · 4498 次点击
```go func Reverse(x int64) int64{ var ret int64 sign := 0 if x < 0{ x = x * -1 sign = 1 } len ,tmp:= 0,x for { if tmp <0 || tmp == 0{ break } len = len + 1 tmp = tmp / 10 } for i:=len ; i>0 ; i--{ j := len -i if j!= 0{ ret = ret * 10 + x% int64(math.Pow10(j + 1)) / int64(math.Pow10(j)) }else{ ret = ret + x % 10 } fmt.Println(i,ret) } if sign != 0{ ret = ret * -1 } return ret; } ```
#11
更多评论
```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