2015年9月16日星期三

Leetcode 9 Palindrome Number

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

Solution 1: if x=1254521, p=1000000. we get i=x/p=1, j=x%10=1, compare i and j. Next, we use x=x%p/10=25452, p=p/100=10000. It is like move i,j from start/end to middle.

 public class Solution {  
   public boolean isPalindrome(int x) {  
     if (x<0) return false;  
     int p=1;  
     //keep not over flow,keep p<x  
     while (x/p>=10) p*=10;  
     while (x!=0) {  
       int i=x/p;  
       int j=x%10;  
       if (i!=j) return false;  
       x=x%p/10;  
       p/=100;  
     }  
     return true;  
   }  
 }  

没有评论:

发表评论