前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【LeetCode题解-009】Palindrome Number

【LeetCode题解-009】Palindrome Number

作者头像
周三不加班
发布2019-09-03 11:22:35
2290
发布2019-09-03 11:22:35
举报
文章被收录于专栏:程序猿杂货铺程序猿杂货铺

代码格式不佳的话请点击下方阅读原文查看

1题目

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121Output: true

Example 2:

Input: -121Output: falseExplanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: 10Output: falseExplanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:

Coud you solve it without converting the integer to a string?

2翻译

判判断一个数是否为回文数,并且不可以使用额外存储空间

3解题思路

  • 对于回文数判断,我最开始想到的是搞一个int型变量temp,用temp来存储输入x的反转,接着将temp与x进行比较,最后通过比较结果来输出true或false。但是题中明确给出了不可以使用额外存储空间的条件,因此此方式不可行
  • 使用字符串,这个方式就很简单了,先把字符串反转,然后判断两者是否相等,相等即为回文数字
  • 查看了下官方答案,用了一种很巧妙的方式,通过以此去比较指定数字的最高位和最低位是否相等来确定是不是回文数字

4解法一

使用字符串来实现,代码比较简洁,也很好理解,源码如下:

/**
     * 直接使用字符串的方式
     * @param x
     * @return
     */
    public static boolean isPalindrome_2(int x) {
        String b = String.valueOf(x);
        StringBuilder before = new StringBuilder(b);
        String after = before.reverse().toString();
        return b.equals(after);
    }

5解法二

使用官网提供的解题思路,逐次去判断给定数字的最高位和最低位是否相等来决定是否为回文数字

public static boolean isPalindrome(int x) {
        int length = 1;
        // 负数 越界肯定不是回文
        if (x < 0 || x > Integer.MAX_VALUE) {
            return false;
        }
        while(x / length >= 10) {
            length *= 10;
        }
        while (x != 0) {
            // x 的最高位
            int left = x / length;
            // x 的最低位
            int right = x % 10;
            // 有不相等的
            if (left != right) {
                return false;
            }
            // 去掉已经比较过得最高位和最低位 如 12345 变成 234
            x = (x % length) / 10;
            // 去除最高位和最低位之后 x 的长度也相应要减少
            length /= 100;
        }
        return true;
    }
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-10-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序员啊粥 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档