[leetcode]9. Palindrome Number

本文介绍两种判断整数是否为回文数的方法:一种是将整数转换为字符串进行判断;另一种是利用队列和栈的数据结构特性进行判断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由于准备要开组会。。研究没啥进展,慌得一笔,开会前找了题简单的练练手。。

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.

这一题就是要求判断一个数是不是回文数,转了字符串就很好办了

只需要分3类如果是负数,直接返回false,是0,返回true,大于0的话,在这基础上再分2类

长度是不是能被2整除,也就是搜索出发点是不是一样。。。然后往两端搜索逐个比较就能出结果了。

这次用的是java,代码如下:

 boolean isPalindrome(int x) {
        if (x < 0)
            return false;

        if (x == 0)
            return true;

        String x_string = new String();
        x_string = String.valueOf(x);

        int left;
        int right;

        if(x_string.length() % 2 != 0){
            left = x_string.length() / 2;
            right = left;
            while(left > 0 && right < x_string.length()){
                left -= 1;
                right += 1;
                if(x_string.charAt(left) != x_string.charAt(right))
                    return false;
            }
        }else{
            left = x_string.length() / 2 - 1;
            right = left + 1;
            while(left >= 0 && right < x_string.length()  ){
                if(x_string.charAt(left) != x_string.charAt(right))
                    return false;
                left -= 1;
                right += 1;
            }
        }

        return true;

    }

我看到题目也有问如果不用字符串能否解决?我认为是可以的。。不过一时没想到,下次贴上代码

_______________________________________________________________________________________

2018.7.19 更新,不使用字符串的方法

其实具体思路差不多,也是把整数分为一位一位去比较,我想起来之前大二学数据结构的队列和栈,用队列和栈就可以解决了

具体思路如下,把整数一位一位地分别存入一个队列和一个栈,由于队列是先进先出,栈是后进先出,这之后我们把队列的元素、栈的元素按顺序拿出来比较就行了,如果是回文数那么从尾到头和从头到尾是一模一样的。具体代码如下:

boolean isPalindrome(int x) {
        Queue<Integer>answerqueue = new LinkedList<Integer>();
        Stack<Integer>answerstack = new Stack<Integer>();
        int temp = 0;

        if(x < 0)
            return false;

        if(x == 0)
            return true;

        while(x > 0){
            temp = x % 10;
            answerqueue.add(temp);
            answerstack.add(temp);
            x /= 10;
        }

        for(int i = 0;i < answerqueue.size();i++){
            if(answerqueue.poll() != answerstack.pop()){
                return false;
            }
        }

        return true;
    }

我也没想到代码反而比使用字符串更短了。。。当然转成字符串也可以使用队列和栈,虽然我认为字符串的优势就是可以直接从中间开始搜索。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值