Count set bits in the Kth number after segregating even and odd from N natural numbers
Last Updated :
01 Mar, 2022
Given two integers N and K, the task is to find the count of set bits in the Kth number in the Odd-Even sequence made of the number from the range [1, N]. The Odd-Even sequence first contains all the odd numbers from 1 to N and then all the even numbers from 1 to N.
Examples:
Input: N = 8, K = 4
Output: 3
The sequence is 1, 3, 5, 7, 2, 4, 6 and 8.
4th element is 7 and the count
of set bits in it is 3.
Input: N = 18, K = 12
Output: 2
Approach: An approach to find the Kth element of the required sequence has been discussed in this article. So, find the required number and then use __builtin_popcount() to find the count of set bits in it.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findK( int n, int k)
{
int pos;
if (n % 2 == 0) {
pos = n / 2;
}
else {
pos = (n / 2) + 1;
}
if (k <= pos) {
return (k * 2 - 1);
}
else
return ((k - pos) * 2);
}
int countSetBits( int n, int k)
{
int kth = findK(n, k);
return __builtin_popcount(kth);
}
int main()
{
int n = 18, k = 12;
cout << countSetBits(n, k);
return 0;
}
|
Java
class GFG
{
static int findK( int n, int k)
{
int pos;
if (n % 2 == 0 )
{
pos = n / 2 ;
}
else
{
pos = (n / 2 ) + 1 ;
}
if (k <= pos)
{
return (k * 2 - 1 );
}
else
return ((k - pos) * 2 );
}
static int countSetBits( int n, int k)
{
int kth = findK(n, k);
int count = 0 ;
while (kth > 0 )
{
count += kth & 1 ;
kth >>= 1 ;
}
return count;
}
public static void main (String[] args)
{
int n = 18 , k = 12 ;
System.out.println(countSetBits(n, k));
}
}
|
Python3
def findK(n, k) :
if (n % 2 = = 0 ) :
pos = n / / 2 ;
else :
pos = (n / / 2 ) + 1 ;
if (k < = pos) :
return (k * 2 - 1 );
else :
return ((k - pos) * 2 );
def countSetBits( n, k) :
kth = findK(n, k);
return bin (kth).count( '1' );
if __name__ = = "__main__" :
n = 18 ; k = 12 ;
print (countSetBits(n, k));
|
C#
using System;
class GFG
{
static int findK( int n, int k)
{
int pos;
if (n % 2 == 0)
{
pos = n / 2;
}
else
{
pos = (n / 2) + 1;
}
if (k <= pos)
{
return (k * 2 - 1);
}
else
return ((k - pos) * 2);
}
static int countSetBits( int n, int k)
{
int kth = findK(n, k);
int count = 0;
while (kth > 0)
{
count += kth & 1;
kth >>= 1;
}
return count;
}
public static void Main (String[] args)
{
int n = 18, k = 12;
Console.WriteLine(countSetBits(n, k));
}
}
|
Javascript
<script>
function findK(n, k)
{
let pos;
if (n % 2 == 0)
{
pos = parseInt(n / 2, 10);
}
else
{
pos = parseInt(n / 2, 10) + 1;
}
if (k <= pos)
{
return (k * 2 - 1);
}
else
{
return ((k - pos) * 2);
}
}
function countSetBits(n, k)
{
let kth = findK(n, k);
let count = 0;
while (kth > 0)
{
count += kth & 1;
kth >>= 1;
}
return count;
}
let n = 18, k = 12;
document.write(countSetBits(n, k));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...