LeetCode【009】Palindrome Number

题目

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

Example 1:

Input: 121
Output: true

Example 2:

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

Example 3:

Input: 10
Output: false
Explanation: 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?

翻译

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

解题思路

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

解法一

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

/**
     * 直接使用字符串的方式
     * @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);
    }

解法二

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

  • ①创建两个int变量left和right;

  • ②left表示当前数x的最高位数字,right表示当前数x的最低位数字;

  • ③若 left == right,则将当前数x去掉最高位和最低位,并且继续执行②,直至 x == 0

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;
    }

Github地址:https://github.com/Bylant/LeetCode

CSDN地址:https://blog.csdn.net/ZBylant
微信公众号 在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值