[LeetCode By Go 101]9. Palindrome Number

題目

Determine whether an integer is a palindrome. Do this without extra space.
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.

解題思路

判斷是否為回文數
從兩端開始比較,先找到最高位和最低位,
最低位,x % 10
最高位,0 < x / 10n < 10 時,x / 10n就是最高位的值, high = 10 n
將最高位和最低位進行比較,然后
x = x % high
x /= 10
high = 10 n-2
去掉最高位和最低位,再進行下一輪比較
注意
x < 0 時都不是回文數
0 < x < 10時都是回文數

代碼

func isPalindrome(x int) bool {
    fmt.Printf("x:%+v\n", x)
    if x < 0 {
        return false
    } else if x < 10 {
        return true
    }

    //取最高位
    high := 10

    for x/high > 9 {
        high *= 10
    }

    for x > 0 {
        fmt.Printf("new_x:%+v, high:%+v\n", x, high)
        numHigh := x / high
        numLow := x % 10
        fmt.Printf("numHigh:%d, numLow:%d\n", numHigh, numLow)
        if numHigh != numLow {
            return false
        }

        x = x % high
        x /= 10
        high /= 100
    }

    return true
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,769評論 0 33
  • 007的各位戰友好,我是微信訂閱號(Water不忘初心)的作者:陳水,名字很好記,陳水扁欠扁就是我的名字(陳水扁少...
    魚水得漁閱讀 285評論 3 4
  • 開始一段挑戰自我、不斷成長的旅程,從心態、意識、起步上都有了平和近乎嘮叨的敘述,萬事俱備,怎么也繞不開行動,因為目...
    塵世知行者閱讀 597評論 2 1