ninehills / blog

https://ninehills.tech
862 stars 80 forks source link

LeetCode-9. Palindrome Number #16

Closed ninehills closed 7 years ago

ninehills commented 7 years ago

20170720

问题

Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

Some hints: Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

思路

回文数类似于 12321,或者 123321。两种思路:

解答

package main

import "fmt"

// ----------------------

func isPalindrome(x int) bool {
    if x < 0 {
        return false
    }
    xx := x
    y := 0
    for x != 0 {
        y = x%10 + y*10
        x = x / 10
    }
    if y == xx {
        return true
    } else {
        return false
    }
}

// ----------------------

func main() {
    fmt.Println(isPalindrome(123123123123123))
    fmt.Println(isPalindrome(922337203))
    fmt.Println(isPalindrome(-123))
    fmt.Println(isPalindrome(12521))
    fmt.Println(isPalindrome(125521))
}