Math-9.Palindrome Number

来源:互联网 发布:matlab二分法求解编程 编辑:程序博客网 时间:2024/06/06 13:04

题目描述:

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.


题目解析

1. 此题想要判断一个数字是不是回文数字。并且要求不能使用额外的辅助空间。即空间复杂度必须是O(1)级别。
2. 思考首先负数有-号,肯定不是回文。然后可以倒着写出这个数来判断与原数是否相等。等于了就是回文数字。时间复杂度O(n)。


代码如下:

class Solution {public:        bool isPalindrome(int x)     {        if(x<0 || x!=0 && x%10==0)        // 如果x是负数或者x是一个10的整数倍的数,那么x都不可能回文            return false;                int sum = 0;        int xx = x, num = 0;        while(x > abs(sum) && num++ < 32)        {            // 可以倒着计算出sum,来比对最终的sum和x,从而判断是否回文;之所以加上num<32,是因为防止x为32位最大整数,此时x永远大于sum,防止陷入死循环。            sum = sum*10 + xx%10;            xx = xx/10;        }                return (x == sum);    }};




原创粉丝点击