VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-a-number-is-bleak/

⇱ Check if a Number is a Bleak - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if a Number is a Bleak

Last Updated : 7 Apr, 2026

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.

Naive Approach - O(n log n) Time and O(1) Space

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

  • Check all values of x from 1 to 3
  • x = 1, countSetBits(1) = 1 then 1 + 1 = 2 != 4
  • x = 2, countSetBits(2) = 1 then 2 + 1 != 4
  • x = 3, countSetBits(3) = 2 then 3 + 2 != 4
  • No value satisfies the condition, so return true

Final answer is true (4 is Bleak).


Output
false
true

Expected Approach - O(log n * log n) Time and O(1) Space

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) = n

Rearranging:
countSetBits(x) = n āˆ’ x

Now, observe that the maximum number of set bits in any number x < n is limited by the number of bits in x, 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

  • Firstly, find ceil(log2(8)) = 3
  • Since countSetBits(x) ≤ 3, we have n āˆ’ x ≤ 3
    So, x ≄ 8 āˆ’ 3 = 5
  • Range reduces to: x from 5 to 7
  • x = 5, countSetBits(5) = 2 then 5 + 2 = 7 != 8
  • x = 6, countSetBits(6) = 2 then 6 + 2 = 8
  • Condition satisfied. So, return false

Final answer is false (8 is not Bleak).


Output
false
true

Note: Most languages provide built-in functions to count set bits, which can simplify the implementation and improve readability.


Output
1
4

Time Complexity: O(log n)
Auxiliary Space: O(1) 

Comment
Article Tags: