Palindrome Number

题目:

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

 

解答:

First, compare the first and last
digit. If they are not the same, it must not be a palindrome. If they are the same, chop off
one digit from both ends and continue until you have no digits left, which you conclude
that it must be a palindrome

 

 1 public boolean isPalindrome(int x) {
 2     if(x < 0) {
 3         return false;
 4     }
 5 
 6     int div = 1;
 7     while(x / div >= 10) {
 8         div = div * 10;
 9     }
10 
11     while(x != 0) {
12         int l = x / div;
13         int r = x % 10;
14         if(l != r) {
15             return false;
16         }
17 
18         x = (x % div) / 10;
19         div = div / 100;
20     }
21 
22     return true;
23 }

 

posted @ 2019-02-21 14:28  林木声  阅读(161)  评论(0编辑  收藏  举报