leetcode:7.Reverse Integer

2018-08-15  本文已影响0人  唐僧取经

7 Reverse Integer

Description

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
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Answer

package main

import (
    "math"
    "fmt"
)

func reverse(x int) int {
    temp := int(math.Abs(float64(x)))

    var result int = 0

    for temp != 0 {
        result = result*10 + temp%10
        temp = temp / 10
    }

    if result>int(math.Pow(2.0,31.0)-1) {
        return 0
    }

    if x < 0 {
        //返回负值
        return -result
    } else {
        return result
    }

}

func main() {
    fmt.Println(reverse(-1230))
}


上一篇 下一篇

猜你喜欢

热点阅读