Leetcode-3 Palindrome Number

文章目录

问题

判断一个整数是否是回文.(跟汉字回文一样, 正反一样).
限制: 不将数字转为字符串.

例子:
Example 1:

Input: 121
Output: true

Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

解决方案

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

复杂度分析:
时间复杂度 : O ( l o g 10 ( n ) ) O(log_{10}(n))
空间复杂度 : O ( 1 ) O(1)

猜你喜欢

转载自blog.csdn.net/creambean/article/details/88737347