Leetcode 9. Palindrome Number

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?

 

这道题考察整数反转,我们可以通过to_string来进行转换成字符串进行做,代码看起来简洁一点。

如果使用另一个数来保存并且判断,也是可以的

class Solution {
public:
    bool isPalindrome(int x) {
        string s = to_string(x);
        for(int i = 0; i < s.length() / 2; i++) 
            if(s[i] != s[s.length() - i - 1]) return false;
        return true;
    }
};

 

posted @ 2020-02-06 18:58  SteveYu  阅读(95)  评论(0编辑  收藏  举报