[leetcode] 9. Palindrome Number

来源:互联网 发布:张子萱淘宝店月收入 编辑:程序博客网 时间:2024/06/05 00:44

题目链接:https://leetcode.com/problems/palindrome-number/

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.

思路

使用数学的方法,通过除余和初的操作来取得最高位和最低位的数字,通过是否相等来判断是否是回文数字

class Solution {public:    bool isPalindrome(int x) {        if(x < 0) return false;        int high = 1,val = x;        while(val >= 10) val = val/10,high *= 10;        while(x > 0){            if(x / high != x % 10) return false;            x = x % high,high /= 100;            x = x / 10;        }        return true;    }};