Count numbers up to N having Kth bit set
Given two integers N and K, the task is to find the count of numbers up to N having K-th (0-based indexing) bit set.
Examples:
Input: N = 14, K = 2
Output: 7
Explanation:
The numbers less than equal to 14, having 2nd bit set are 4, 5, 6, 7, 12, 13, and 14.
Input: N = 6, K = 1
Output: 3
Explanation:
The numbers less than equal to 6 having 1st bit set are 1, 3, 5.
Naive Approach: The simplest approach is to traverse from 1 to N, and check for each number whether its K-th bit is set or not.
Time Complexity: O(N)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized by dividing the task into two parts:
- First, right shift N, K+1 times followed by left shifting the result K times, which gives the count of numbers satisfying the given condition till the nearest power of 2 less than N.
- Now, check if the Kth bit is set in N or not.
- If the Kth bit is set in N, then add the count of numbers from the nearest power of 2 less than N to the answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
long long getcount( long long n, int k)
{
long long res = (n >> (k + 1)) << k;
if ((n >> k) & 1)
res += n & ((1ll << k) - 1);
return res;
}
int main()
{
long long int N = 14;
int K = 2;
cout << getcount(N + 1, K) << endl;
return 0;
}
|
Java
class GFG
{
static long getcount( long n, int k)
{
long res = (n >> (k + 1 )) << k;
if (((n >> k) & 1 ) != 0 )
res += n & (( 1 << k) - 1 );
return res;
}
public static void main(String[] args)
{
long N = 14 ;
int K = 2 ;
System.out.println(getcount(N + 1 , K));
}
}
|
Python3
def getcount(n, k):
res = (n >> (k + 1 )) << k
if ((n >> k) & 1 ):
res + = n & (( 1 << k) - 1 )
return res
if __name__ = = '__main__' :
N = 14
K = 2
print (getcount(N + 1 , K))
|
C#
using System;
class GFG{
static long getcount( long n, int k)
{
long res = (n >> (k + 1)) << k;
if (((n >> k) & 1) != 0)
res += n & ((1 << k) - 1);
return res;
}
static void Main()
{
long N = 14;
int K = 2;
Console.WriteLine(getcount(N + 1, K));
}
}
|
Javascript
<script>
function getcount(n, k)
{
let res = (n >> (k + 1)) << k;
if (((n >> k) & 1) != 0)
res += n & ((1 << k) - 1);
return res;
}
let N = 14;
let K = 2;
document.write(getcount(N + 1, K));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Last Updated :
31 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...