📌  相关文章
📜  在[0,n]范围内只有1个置位的数字的计数

📅  最后修改于: 2021-04-26 06:06:35             🧑  作者: Mango

给定一个整数n ,任务是对范围为[0,n]的仅具有1个设置位的数字进行计数。
例子:

方法:如果需要k个位来表示n,则可能有k个数,因为每次1可以位于k个不同的位置
下面是上述方法的实现

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the required count
int count(int n)
{
 
    // To store the count of numbers
    int cnt = 0;
    int p = 1;
    while (p <= n) {
        cnt++;
 
        // Every power of 2 contains
        // only 1 set bit
        p *= 2;
    }
    return cnt;
}
 
// Driver code
int main()
{
    int n = 7;
    cout << count(n);
 
    return 0;
}


Java
// Java implementation of the approach
class GFG {
 
    // Function to return the required count
    static int count(int n)
    {
 
        // To store the count of numbers
        int cnt = 0;
        int p = 1;
        while (p <= n) {
            cnt++;
 
            // Every power of 2 contains
            // only 1 set bit
            p *= 2;
        }
        return cnt;
    }
 
    // Driver code
    public static void main(String args[])
    {
        int n = 7;
        System.out.print(count(n));
    }
}


C#
// C# implementation of the approach
using System;
class GFG {
 
    // Function to return the required count
    static int count(int n)
    {
 
        // To store the count of numbers
        int cnt = 0;
        int p = 1;
        while (p <= n) {
            cnt++;
 
            // Every power of 2 contains
            // only 1 set bit
            p *= 2;
        }
        return cnt;
    }
 
    // Driver code
    public static void Main()
    {
        int n = 7;
        Console.Write(count(n));
    }
}


Python3
# Python3 implementation of the approach
 
# Function to return the required count
def count(n):
     
    # To store the count of numbers
    cnt = 0
    p = 1
    while (p <= n):
        cnt = cnt + 1
         
        # Every power of 2 contains
        # only 1 set bit
        p *= 2
    return cnt
 
# Driver code
n = 7
print(count(n));


PHP


Javascript


输出:
3

时间复杂度: O(log n)