Palindrome Number

Description

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

在不使用额外空间的条件下判断一个整型是否为回文

我认为这是一个伪命题(wtf? without extra space?)

Solution

Pretty solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
func isPalindrome(x int) bool {
    if x < 0 || (x != 0 && x%10 == 0) {
        return false
    }

    sum := 0
    for x > sum {
        sum = sum * 10 + x % 10
        x = x / 10
    }
    return (x == sum) || (x == sum / 10)
}

My solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
func isPalindrome(x int) bool {
    if x < 0 {
        return false
    }

    if x < 10 {
        return true
    }

    // get len(string(x)) - 1
    l := 0
    for i := x; i >= 10; i /= 10 {
        l++
    }

    mod := 1
    for i := 0; i < l; i++ {
        mod *= 10
    }

    lnum, rnum := x, x
    for i := 0; i < (l + 1) / 2; i++ {
        fmt.Println(lnum, rnum)

        l := lnum / mod
        r := rnum - (rnum / 10 * 10)

        lnum = lnum - (l * mod)
        mod /= 10

        rnum /= 10

        fmt.Println(l, r)
        if l != r {
            return false
        }
    }

    return true
}