Given an integer n, the task is to count the numbers having only 1 set bit in the range [0, n].
Examples:
Input: n = 7
Output: 3
Explanation: 000, 001, 010, 011, 100, 101, 110 and 111 are the binary representation of all the numbers upto 7. And there are only 3 numbers ( 001, 010 and 100 ) having only 1 set bit.
Input: n = 3
Output: 2
Approach: If k bits are required to represent n then there are k numbers possible as 1 can be positioned at k different positions each time.
Below is the implementation of the above approach
C++
#include <bits/stdc++.h>
using namespace std;
int count( int n)
{
int cnt = 0;
int p = 1;
while (p <= n) {
cnt++;
p *= 2;
}
return cnt;
}
int main()
{
int n = 7;
cout << count(n);
return 0;
}
|
Java
class GFG {
static int count( int n)
{
int cnt = 0 ;
int p = 1 ;
while (p <= n) {
cnt++;
p *= 2 ;
}
return cnt;
}
public static void main(String args[])
{
int n = 7 ;
System.out.print(count(n));
}
}
|
C#
using System;
class GFG {
static int count( int n)
{
int cnt = 0;
int p = 1;
while (p <= n) {
cnt++;
p *= 2;
}
return cnt;
}
public static void Main()
{
int n = 7;
Console.Write(count(n));
}
}
|
Python3
def count(n):
cnt = 0
p = 1
while (p < = n):
cnt = cnt + 1
p * = 2
return cnt
n = 7
print (count(n));
|
PHP
<?php
function count_t( $n )
{
$cnt = 0;
$p = 1;
while ( $p <= $n )
{
$cnt ++;
$p *= 2;
}
return $cnt ;
}
$n = 7;
echo count_t( $n );
?>
|
Javascript
<script>
function count(n)
{
var cnt = 0;
var p = 1;
while (p <= n) {
cnt++;
p *= 2;
}
return cnt;
}
var n = 7;
document.write(count(n));
</script>
|
Time Complexity: O(log n)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
07 Dec, 2022
Like Article
Save Article