码迷,mamicode.com
首页 > 其他好文 > 详细

9. Palindrome Number【数学】

时间:2017-03-30 22:45:43      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:eterm   min   lag   line   whether   out   数字   with   extra   

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【数学】

标签:eterm   min   lag   line   whether   out   数字   with   extra   

原文地址:http://www.cnblogs.com/flyfatty/p/6648850.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!