#3677
Count Binary Palindromic Numbers
HardMathBit ManipulationBit ManipulationDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n log n) | O(log n * 2^(log n / 2)) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(log n * 2^(log n / 2))Space O(1)
Instead of checking each number, count palindromic binaries based on their lengths. The first half determines the whole binary palindrome.
⚙️
Algorithm
3 steps- 1Step 1: Determine the maximum length of binary representation for n.
- 2Step 2: For each length, generate palindromic numbers by constructing the first half and mirroring it.
- 3Step 3: Count valid palindromic numbers that are <= n.
solution.py7 lines
1def countBinaryPalindromes(n):
2 count = 0
3 for length in range(1, n.bit_length() + 1):
4 for half in range(1 << (length // 2)):
5 pal = (half << (length // 2)) | int(bin(half)[:length // 2][::-1], 2)
6 if pal <= n: count += 1
7 return countℹ
Complexity note: The outer loop runs log n times, and the inner loop generates palindromes based on half-length.
- 1Binary representation length is crucial.
- 2First half of the binary number defines the palindrome.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.