验证回文数字

题目描述:
Determine whether an integer is a palindrome. An integer is a
palindrome when it reads the same backward as forward.

Follow up:

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

解题思路:
方法一:
step1:若该整数为负,则必不是回文数字
step2:若该整数位0,则必为回文数字
step3:在该整数为正数的情况下,将每一位数字按顺序存储在数组里,若为回文,则必满足镜像对称.
时间复杂度为O(n)(n为x的位数)
代码如下:

class Solution {
    public boolean isPalindrome(int x) {
        if(x<0) return false;
        if(x==0)    return true;
        int[] p = new int[];
        int i=0;
        while(x!=0){
            p[i++]=x%10;
            x/=10;
        }
        for(int j=0;j<(i+1)/2;j++){
            if(p[j]!=p[i-j-1])  return false;
        }
        return true;
    }
}

方法二:
借助一个反向整数来验证。
step1:如果该整数为负或非零但末位为零,则必不是回文数字。
step2:从低位到高位构建该整数的反向整数,直到反向整数的位数为原数字的一半(偶数位)或一半+1(基数位),同时舍弃x的低位。若x与反向数组相等,则为回文数字。
代码如下:

class Solution {
    public boolean isPalindrome(int x) {
        if(x<0||(x%10==0&&x!=0))    return false;
        int rev = 0;
        while(x>rev){
            rev=rev*10+x%10;
            x/=10;
        }
        return x==rev||x==rev/10;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值