首页 > 代码库 > 9. Palindrome Number【数学】
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 ;
}
}
9. Palindrome Number【数学】
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。