![]() |
VOOZH | about |
Given an integer n, check whether it is Bleak or not. A number 'n' is called Bleak if it cannot be represented as sum of a positive number x and count of set bits in x, i.e., x + countSetBits(x) is not equal to n for any non-negative number x.
Examples:
Input: n = 3
Output: false
Explanation: For x = 2, countSetBits(2) = 1
2 + 1 = 3
So, 3 is not Bleak.
Input: n = 4
Output: true
Explanation:
There is no value of x such that x + countSetBits(x) = 4
So, 4 is Bleak.
Table of Content
Checks all values of x from 1 to nā1. If any x satisfies x + countSetBits(x) = n, then n is not Bleak. If no such x exists, then n is Bleak.
Dry run for n = 4
Final answer is true (4 is Bleak).
false true
The maximum number of set bits in any number less than n is at most ceil(log2(n)). So, instead of checking all values, we only need to check numbers in the range n - ceil(log2(n)) to n - 1.
How does this work?
We need to satisfy:
x + countSetBits(x) = nRearranging:
countSetBits(x) = n ā xNow, observe that the maximum number of set bits in any number
x < nis limited by the number of bits inx, which is at most:
ceil(log2(n))So:
countSetBits(x) ⤠ceil(log2(n))This gives:
n ā x ⤠ceil(log2(n))Rearranging:
x ā„ n ā ceil(log2(n))
Dry run for n = 8
Final answer is false (8 is not Bleak).
false true
Note: Most languages provide built-in functions to count set bits, which can simplify the implementation and improve readability.
1 4
Time Complexity: O(log n)
Auxiliary Space: O(1)