Leetcode-Palindrome Number

来源:互联网 发布:linux拷贝当前目录 编辑:程序博客网 时间:2024/05/29 11:43

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

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.


题目给出一个数字,判断该数字是否是回文结构,即该数字从左往右看,或,从右往左看,是一样的。按照题目要求,不处理负数。虽然题目写着不能使用额外空间,但确实可以创建一个变量。原题评论里也有人在问“the restriction of using extra space”究竟算是啥意思,不是很懂,反正先做下去再说。

方法比较简单,直接提取数字的末位,构造新的数字,再比较是否相等。若新数字等于原数字,则原数字是回文。要注意,每次都要去掉原数字的末位,以便取得“新的”末位。

class Solution_1 {public:    bool isPalindrome(int x) {        if(x < 0 || (x%10 == 0 && x != 0)) {        return false;        }int t = 0;int k = x;while(k > 0) {t = t*10 + k%10;k = k/10;}return x==t || x == t/10;    }};

另一个更加直观的方法是,每次提取数字的首位和末位,判断是否相等。

class Solution_2{public:    bool isPalindrome(int x) {        if(x < 0 || (x%10 == 0 && x != 0)) {        return false;        }        int t = 1;        while(t <= x) {        t = t*10;        }        t = t/10;        while(x > 0) {        if(x%10 != x/t) {        return false;        }        x = x%t;//去掉第一位         x = x/10;//去掉最后一位         t = t/10;        }        return true;    }};


原创粉丝点击