Skip to content

Commit 5ff7b88

Browse files
committed
Time: 6 ms (70.43%), Space: 65.2 MB (57.51%) - LeetHub
1 parent fd05fab commit 5ff7b88

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

0009-palindrome-number/Solution.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Mathematical Digit Reversal | 12 Lines | O(log n) | 4ms
2+
3+
# Intuition
4+
A palindrome reads the same forwards and backwards. For a number to be a palindrome, its reverse should equal the original number. Negative numbers cannot be palindromes since the negative sign appears only at the beginning. We can reverse the number mathematically by repeatedly extracting the last digit and building up the reversed number.
5+
6+
# Approach
7+
I'll use mathematical digit manipulation to reverse the number:
8+
9+
1. **Handle Negative Numbers**: Return false immediately for negative numbers since they cannot be palindromes (the negative sign only appears at the start).
10+
11+
2. **Mathematical Reversal**: Reverse the number using modular arithmetic:
12+
- Extract the last digit using `workingNumber % 10`
13+
- Add it to the reversed number after shifting previous digits left by multiplying by 10
14+
- Remove the processed digit using `Math.floor(workingNumber / 10)`
15+
- Repeat until all digits are processed
16+
17+
3. **Comparison**: Compare the fully reversed number with the original to determine if it's a palindrome.
18+
19+
4. **No String Conversion**: This approach avoids string conversion, working purely with mathematical operations.
20+
21+
This method is efficient and handles all edge cases naturally, including single digits (which are palindromes) and numbers ending in zero.
22+
23+
# Complexity
24+
- Time complexity: $$O(\log n)$$
25+
- Number of iterations equals the number of digits in n
26+
- Each iteration performs constant-time operations
27+
- Number of digits is logarithmic in the value of n
28+
29+
- Space complexity: $$O(1)$$
30+
- Only using constant extra variables for the working number and reversed result
31+
- No additional data structures that scale with input size
32+
- All operations performed with primitive arithmetic
33+
34+
# Code
35+
```typescript []
36+
const isPalindrome = (x: number): boolean => {
37+
if (x < 0) {
38+
return false;
39+
}
40+
41+
let workingNumber = x;
42+
let reversedNumber = 0;
43+
44+
while (workingNumber !== 0) {
45+
reversedNumber = reversedNumber * 10 + workingNumber % 10;
46+
workingNumber = Math.floor(workingNumber / 10);
47+
}
48+
49+
return reversedNumber === x;
50+
};
51+
```

0 commit comments

Comments
 (0)