【整数转字符串】LeetCode 9. Palindrome Number

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Allenlzcoder/article/details/81585707

LeetCode 9. Palindrome Number

Solution1:
不利用字符串

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) return false;
        int res = 0, base = 1, x_copy = x;
        while (x_copy) {
            res = res * 10 + x_copy%10;
            x_copy /= 10;
        }
        if (res != x)
            return false;
        else
            return true;
    }
};

Solution2:
利用字符串
就是有点慢!

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) return false;
        string str_x = to_string(x);
        int left = 0, right = str_x.size() - 1;
        while (left < right) {
            if (str_x[left] != str_x[right])
                return false;
            else {
                left++;
                right--;
            }
        }
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/Allenlzcoder/article/details/81585707
今日推荐