1523. Binary Mirror Test
A jeweller stamps each pendant with a positive serial number n, and a pendant is considered balanced when the binary form of its serial, written without leading zeros, reads the same from left to right as from right to left. For instance 9 is 1001, which is balanced, while 6 is 110, which is not.
Given n, return true if the pendant is balanced and false otherwise. Work with shifts and masks only: repeatedly compare the highest and the lowest bits that have not been checked yet and move inward from both ends, rather than building and reversing a string. Note that n can be as large as 10^15, so use a 64-bit type. The intended running time is O(log n) with O(1) extra space (or O(log n) if you keep the bits).
Example 1
- Input:
- n = 9
- Output:
- true
- Explanation:
9 is 1001 in binary, which reads the same both ways.
Example 2
- Input:
- n = 6
- Output:
- false
- Explanation:
6 is 110 in binary, which reversed is 011, so it is not a mirror.
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(1)