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?

 

my code:

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) return false;
        stringstream ss;
        ss << x;
        string str = ss.str();
        int len = str.length();
        int l, r;
        if (len % 2 != 0)
            r = l = len / 2;
        else {
            r = len / 2;
            l = r - 1;
        }
        while (r < len && l >= 0) {
            if (str[r] != str[l])
                return false;
            r++;
            l--;
        }
        return true;
    }
};

Runtime: 172 ms, faster than 33.22% of C++ online submissions for Palindrome Number.

there are some ways to convert int to string:

(1)

int a = 10;
char *intStr = itoa(a);
string str = string(intStr);
(2)

int a = 10;
stringstream ss;
ss << a;
string str = ss.str();

(3)
auto s = std::to_string(42);

 


 

when i finshed it, i found the hint in the bottom of the question. Coud you solve it without converting the integer to a string?

 

this is my second way:

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) return false;
        int num = x;
        int ans = 0;
        while (num) {
            ans = ans * 10 + num % 10;
            num /= 10;
        }
        if (ans == x) return true;
        else return false;
    }
};

Runtime: 152 ms, faster than 47.48% of C++ online submissions for Palindrome Number.

 

posted @ 2018-09-28 21:17  Veritas_des_Liberty  阅读(185)  评论(0编辑  收藏  举报