9. Palindrome Number(C++)

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

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.

Follow up:

Coud you solve it without converting the integer to a string?


题目大意:

  判断一个数是否是回文,并且不能转换成string来解决。

解题思路:

  转换成string,直接循环一边判断头尾是最简单直接的方法,但是题目限定不能使用string,那就只能在int上面想。思路和整数转置(https://www.jianshu.com/p/a63cf3aefb5f
)有点类似,将原来的整数从逐步剥离处理。

解题代码:


class Solution {
public:
   bool isPalindrome(int x) {
    if (x < 0 || (x % 10 == 0 && x != 0))
        return false;

    int reverseNum = 0;

    while (x > reverseNum)
    {
        reverseNum = reverseNum * 10 + x % 10;
        x /= 10;
    }

    return x == reverseNum || x == reverseNum / 10;
}
};

你可能感兴趣的:(9. Palindrome Number(C++))