LeetCode【9】. Palindrome Number --java的实现

Palindrome Number

 
Determine whether an integer is a palindrome. Do this without extra space.
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.

       判断一个int是否为回文。

一、思路1:

       首先获取int长度,再从两头往中间扫描,将对称的元素成对进行比较。代码如下,但是Time Limit Exceeded超时了。

public class Solution {
    public boolean isPalindrome(int x) {
        int xl;
        
        if(x<0)                       //1.小于0
            return false;
            
        for(xl = 1;x/(xl*10)>0;xl++)  //2. 得到x的长度
           ;
        
        if(xl==1)                     //3.x为个位数时直接返回(因为后续处理个位数时会使分母为0,故单独处理)
          return true;
          
        for(int i=2;(xl/2)>=i;i++) 
        {
            if(x%(i*10)/((i-1)*10) == x%((xl-i+1)*10)/((xl-i)*10))  //4.分别取对称的两个数进行比较
            {
                
            }else
               return false;
        }
        return true;
        
    }
}

       

二、思路2

       复制将给定int从低位往高位开始,复制为另外一个高位至低位,得到一个给定值的反序。再比较两者是否相等。意思就是拿个镜子,然后照出镜子里跟自己左右相反的自己。如果是自己是完全对称的(这里是回文),那例外两个看一起一定一模一样的。

Java代码如下:

public class Solution {
    public boolean isPalindrome(int x) {
        int t=x;      
        int re=0;  
        
        if(x<0)             //1. 负数无法为回文
            return false;

        while(t>0)          //2. 判断是否将t的所有位数取完
        {
          re = re*10+t%10;  //3. 将t的最后一位拼接在re的后面
          t = t/10;
        }
        
        return x==re;       //4. 将两数进行比较并返回结果
    }
}


参考:[LeetCode] 判断一个数字是否为回文数





评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值