[LeetCode]Palindrome Number,解题报告

本文介绍了一种不使用额外空间判断整数是否为回文的方法。提供了两种解决方案:一种是将整数转换为字符串进行比较;另一种是直接对整数进行操作,通过获取最高位和最低位进行比较。

题目

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

click to show spoilers.

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.

思路

1、判断字符串是否为回文是非常普遍的面试题目了,从两边向中间遍历即可,因此这道题目我们可以首先考虑这种做法
  • 通过Integer类的toString方法,将x转为字符串
  • 然后从两边向中间扫描即可

代码:

public static boolean isPalindromeII(int x) {
    if (x < 0) {
        return false;
    }

    String str = Integer.toString(x);
    boolean flag = true;

    for (int i = 0, j = str.length() - 1; i < j; i++, j--) {
        if (str.charAt(i) != str.charAt(j)) {
            flag = false;
            break;
        }
    }

    return flag;
}

这种做法在LeetCode上是可以ac的(ps:亲测),但是题目规定不允许采用直接转成字符串的做法,.......

2、通过转字符串的思路,我们可以考虑到,是否也可以从两边向中间遍历整数,答案是当然可以
  • 获取当前x的长度
  • 取最高位和最低位比较,相等继续,不相等返回false
  • 取次高位和第二位比较,......
  • ......,直接循环len / 2次为止

代码:

public class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0) {
            return false;
        }
        
        int hp, sp, len, tmp;
        
        // determine the length of x
        hp = 1; len = 0; sp = 1; tmp = x;
        while (x > 0) {
            len ++;
            x /= 10;
            if (x > 0) {
                hp *= 10;
            }
        }
        
        // check isPalidrome
        boolean flag = true;
        for (int i = 0; i < len / 2; i ++, hp /= 10, sp *= 10) {
            // fetch high number and low number
            int high = (tmp / hp) % 10;
            int low = (tmp / sp) % 10;
            if (high != low) {
                flag = false;
                break;
            }
        }
        
        return flag;
    }
}

后记

周四收到云os的leader的电话,搞手机安全方面,哈哈,我个人还是很感兴趣的,基本上是c、c++编程,这个有点小郁闷,最近花了两个月的时间学习java,没想到是用c++,不过无所谓了,加油学习就好了

牢记一句话,“以多数人的努力程度之低,根本轮不到拼天赋


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

低调小一

您的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值