Count Binary Palindromic Numbers Problem
#3677
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3677.
You are given a non-negative integer n.
A non-negative integer is called binary-palindromic if its binary representation (written without leading zeros) reads the same forward and backward.
Return the number of integers k such that 0 <= k <= n and the binary representation of k is a palindrome.
Note: The number 0 is considered binary-palindromic, and its representation is "0".
Example 1:
Input: n = 9
Output: 6
Explanation:
The integers k in the range [0, 9] whose binary representations are palindromes are:
- 0 → "0"
- 1 → "1"
- 3 → "11"
- 5 → "101"
- 7 → "111"
- 9 → "1001"
All other values in [0, 9] have non-palindromic binary forms. Therefore, the count is 6.
Example 2:
Input: n = 0
Output: 1
Explanation:
Since "0" is a palindrome, the count is 1.
Constraints:
0 <= n <= 10^15
Solution
Approach: Count by Length, Then Compare the Half
Count 0 separately, then count palindromes by their binary length.
- For a length
lshorter than the lengthLofn, a palindrome is determined by its firstceil(l / 2)bits, which start with 1. That gives2^(ceil(l / 2) - 1)palindromes of lengthl. - For length
L, leth = ceil(L / 2)and letprefixbe the firsthbits ofn. Every half from2^(h-1)up toprefix - 1gives a palindrome smaller thann, which isprefix - 2^(h-1)palindromes. The half equal toprefixgives one more palindrome, but only if the palindrome built from it is at mostn: build it by mirroringprefix(without repeating the middle bit whenLis odd) and compare withn.
Since n <= 10^15 < 2^50, there are at most 50 lengths and everything fits in 64-bit integers.
Complexity: O(log n) time and O(1) extra space.
class Solution:
def countBinaryPalindromes(self, n: int) -> int:
if n == 0:
return 1
length = n.bit_length()
ans = 1 # the number 0
for l in range(1, length): # all palindromes that are shorter than n
ans += 1 << ((l + 1) // 2 - 1)
half = (length + 1) // 2
prefix = n >> (length - half) # the first half of n's bits
ans += prefix - (1 << (half - 1)) # palindromes whose first half is smaller
bits = bin(prefix)[2:]
pal = int(bits + bits[::-1][length % 2:], 2) # the palindrome with the same first half
return ans + (pal <= n)