首页 > 代码库 > 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)
  1. public class Solution {
  2. public boolean isPalindrome(int x) {
  3. if( x < 0 ) return false;
  4. int i = 1 , j = 10 ;
  5. while( x / i >= 10 ) i *= 10 ;
  6. int flag = i;
  7. while( flag >1 ){
  8. if( x/i%j != x%j ) return false;
  9. x /= j;
  10. i /= 100;
  11. flag /= 100;
  12. }
  13. return true;
  14. }
  15. }

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

9. Palindrome Number【数学】