[LeetCode] 9.Palindrome Number

来源:互联网 发布:淘宝细节描述文案 编辑:程序博客网 时间:2024/05/17 03:12


继续水一发 

https://leetcode.com/problems/palindrome-number/

回文数字的判断  考虑到空间 时间

转化为字符串 消耗空间 

数字翻转  可能溢出

直接得出最高位和最低位进行判断 


Palindrome Number

My Submissions
Total Accepted: 82714 Total Submissions: 285137 Difficulty: Easy

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.

代码如下:

<span style="font-size:18px;">class Solution {public:    bool isPalindrome(int x) {        if(x < 0) return false;        int len = 0;        int temp = x;        while(temp){            temp = temp / 10;            len ++;        }        if(len == 1) return true;        int rat1 = 1,first,last;        len = len - 1;        while(x || len > 1){            for(int i = 0; i < len ; i ++)                rat1 *= 10;            first = x / rat1;            last  = x % 10;            if(first != last) return false;            else{                x = x % rat1;                x = x /10;                rat1 = 1;                len -= 2;            }        }        return true;    }};</span>



0 0
原创粉丝点击