1539. Binary Mirrors Up To N

Medium3.5 points estimatedBit ManipulationCombinatoricsMaths

A jeweller stamps binary codes onto bracelets, and a code is considered a mirror when its binary digits read the same from left to right and right to left, with no leading zeros. The number 9 (1001) is a mirror, while 6 (110) is not.

Given a positive integer n, return how many integers in the range [1, n] have a binary representation that is a mirror. For instance, up to 10 the mirrors are 1, 3, 5, 7 and 9, so the answer is 5.

Enumerating all numbers is impossible for large n. A mirror is fully decided by its first half, so count the halves for shorter lengths directly, then handle the length of n itself by comparing halves. Your solution should run in time proportional to the bit length of n and use constant extra space.

Example 1

Input:
n = 10
Output:
5
Explanation:

The binary mirrors up to 10 are 1, 3, 5, 7 and 9.

Example 2

Input:
n = 31
Output:
10
Explanation:

Mirrors have 1, 1, 2, 2 and 4 members of lengths 1 to 5 (for example 1, 11, 101 and 111), giving 10.

Constraints

1 ≤ n ≤ 1015

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(log n)
Space
O(log n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…