Palindrome Number

来源:互联网 发布:淘宝主店铺子店铺 编辑:程序博客网 时间:2024/05/29 15:07

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

开始的解决思路是将整数转换成字符串处理。

 public boolean isPalindrome(int x) {        String str=String.valueOf(x);        int start=0,end=str.length()-1;        while(start<end&&str.charAt(start)==str.charAt(end)){        start++;        end--;        }        if(start==end||start-1==end)        return true;        else        return false;    }

但题目要求不能使用额外空间,显然是不符合要求。
同时也没有考虑对于负数的处理。

public static boolean isPalindrome(int x) {//negativenumbersarenotpalindromeif (x <0)return false;// initialize how many zerosintdiv= 1;while (x / div >= 10) {div*= 10;}while (x !=0) {intleft = x / div;//最高位intright =x %10;//最低位if (left !=right)return false;x =(x % div) /10;//更新除数和被除数div/= 100;}return true;}



0 0
原创粉丝点击