[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,779评论 0 33
  • 007的各位战友好,我是微信订阅号(Water不忘初心)的作者:陈水,名字很好记,陈水扁欠扁就是我的名字(陈水扁少...
    鱼水得渔阅读 287评论 3 4
  • 开始一段挑战自我、不断成长的旅程,从心态、意识、起步上都有了平和近乎唠叨的叙述,万事俱备,怎么也绕不开行动,因为目...
    尘世知行者阅读 597评论 2 1