9. Palindrome Number【数学】

2017/3/30 21:49:57

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

 
版本1:要求不能用额外空间说明不能建立数组存每个数字,只能依靠运算符。
1、需要额外考虑负数情况;
2、从两边开始取出数字依次比较;
时间 O(n)  空间 O(1)
public class Solution {
    public boolean isPalindrome(int x) {
        if( x < 0 ) return false;
		int i = 1 , j = 10 ;
        while( x / i >= 10 ) i *= 10 ;
        int flag = i;
        while( flag >1 ){
        	if( x/i%j != x%j ) return false;
        	x /= j;
        	i /= 100;
        	flag /= 100;
        }
        return true;
    }
}

  

版本2(优先版本): 构建给定数字的相反序列,判断两个数字。优先考虑尾数为0的情况。
1、可以优化为只构建一半的序列,需要考虑奇偶位数。
 
public class Solution {
    public boolean isPalindrome(int x) {
        if( x < 0 || x!=0 && x%10==0 ) return false;
		int build = 0;
        while( x > build ){
        	build = build * 10 + x % 10;
        	x /= 10;
        }
        return build == x || build/10 == x ;
    }
}

  

 

转载于:https://www.cnblogs.com/flyfatty/p/6648850.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值