9. Palindrome Number

来源:互联网 发布:朗读女语音软件 编辑:程序博客网 时间:2024/06/05 17:47

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

click to show spoilers.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

思想:回文数判断,题目中要求不占用额外空间,所以integer转化成string调用翻转函数不可使用

此外也应该考虑之前题目reverse integer中的问题,翻转后有溢出可能,所以也不可取

负数不属于回文数,个位数属于回文数

本题目主要是考察/和% 运算,数123404321,首先位数为9位,首先设立left=10^8  right=1

那么数x/left%10就为最左边的数字,x/right%10为最右边的数字

接下来:left=left/10 就是10^7  right=right*10就是10 在进行上述运算,则为最左最右第二个数字,以此执行


 public boolean isPalindrome(int x) {         if(x>=0&&x<10) return true;        if(x<0) return false;        int n=x;        int bit=0;        while(n>0){        n=n/10;        bit++;//位数        }        int left=(int)Math.pow(10,bit-1);        int right=1;        while(left>=right){        int a=x/left%10;        int b=x/right%10;        //System.out.println(a+"\t"+b);        if(a!=b){        return false;        }        left=left/10;        right=right*10;        }        return true;    }




0 0
原创粉丝点击