Leetcode-palindrome-number

来源:互联网 发布:pdf电子书 知乎 编辑:程序博客网 时间:2024/06/11 08:51

题目描述


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?

There is a more generic way of solving this problem.

这题目本身并不难,判断一个整数是不是回文,但是题目中限制条件很多,如果将整数转为string或者数组处理,都需要额外的空间,不符合条件。我们利用如下方法,计算出倒置后的数,如果和原来的数相等,则是回文数,否则不是回文数。

public class Solution {    public boolean isPalindrome(int x) {        int res = 0;        int s = x;        while(s > 0){            res = res*10+s%10;            s = s/10;        }        if(res == x)            return true;        else            return false;    }}


0 0
原创粉丝点击