This is one of those problems where the clean idea matters more than the amount of code. For 9. Palindrome Number, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: straightforward implementation.
Guide
When?
This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are isPalindrome.
Guide
Why?
The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Start from the smallest reliable state.
- Expand one legal move at a time.
- Cache, count, or merge information as soon as it becomes settled.
- Let the final stored value answer the original question.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(\log_{10}(n)). We divided the input by 10 for every iteration, so the time complexity is O(\log_{10}(n))
- Space: O(1).
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 48 ms, faster than 91.08% of C++ online submissions for Palindrome Number.
02//Memory Usage: 8.2 MB, less than 99.22% of C++ online submissions for Palindrome Number.
03
04class Solution {
05public:
06 bool isPalindrome(int x) {
07 string s = to_string(x);
08 int N = s.size();
09 for(int i = 0; i < N; i++){
10 if(s[i] != s[N-1-i]) return false;
11 }
12 return true;
13 }
14};
15
16/**
17Approach 1: Revert half of the number
18**/
19
20/**
21Complexity Analysis
22Time complexity : O(\log_{10}(n)). We divided the input by 10 for every iteration, so the time complexity is O(\log_{10}(n))
23Space complexity : O(1).
24**/
25
26/**
27class Solution {
28public:
29 bool isPalindrome(int x) {
30 //if x is negative, there will be a '-' sign
31 //if x's last digit is 0, then x must be 0
32 if(x < 0 || (x != 0 && x%10 == 0)) return false;
33
34 int reverted = 0;
35 //construct reverted number of last half of x
36 //do until reverted >= x
37 while(x > reverted){
38 reverted = reverted*10 + x%10;
39 x/=10;
40 }
41
42 //if x has odd digits,
43 //we need to use /10 to get rid of the middle digit
44 //(which is last digit in reverted)
45 return x==reverted || x==reverted/10;
46 }
47};
48**/
Cost