【One question per day】 Number of palindromes

https://leetcode-cn.com/problems/palindrome-number/
Palindrome Number
Determine whether an integer is a palindrome number. The number of palindromes refers to integers that read in the same order (from left to right) and reverse order (from right to left).

Example 1:

Input: 121
Output: true
Example 2:

Input: -121
Output: false
Explanation: Reading from left to right is -121. From right to left, it is 121-. Therefore it is not a palindrome.
Example 3:

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


Solution 1

8ms 6.1mb

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) {
        	return false;
        }

        long int res = 0, my_x = x;
        while (x != 0) {
        	int d = x % 10;
        	res = res * 10 + d;
        	x = x / 10;
        }
        if (res == my_x) {
        	return true;
        } else {
        	return false;
        }
    }
};

Solution 1.5


A judgment [0, 10)is added at 20ms 5.9mb , it can directly return true, if there is something similar to 100, 1000, etc. directly returns false.
Compared to solution one, I initially thought it would be faster, so I didn't need to loop.
In fact, it is also time-consuming to judge the need to calculate in the test case.

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

        long int res = 0, my_x = x;
        while (x != 0) {
        	int d = x % 10;
        	res = res * 10 + d;
        	x = x / 10;
        }
        printf("res %d\n", res);

        return res == my_x;
    }
};

Solution 2

Convert to a string to solve.
Of course, you can also use the stack, but I don't need it, just judge.
If you use the stack, you have to go through O (n). I only need to go through O (n / 2) in this way, but the time complexity is actually O (n).
28ms, 6mb

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

        std::string x_str = std::to_string(x);
        int start = 0;
        int end = x_str.size() - 1;
        while (start < end) {
        	if (x_str[start] != x_str[end]) {
        		return false;
        	}
        	start ++;
        	end --;
        }

        return true;
    }
};

EOF

98 original articles have been published · 91 praises · 40,000+ views

Guess you like

Origin blog.csdn.net/Hanoi_ahoj/article/details/105299462