📌  相关文章
📜  设置了第 0 位和第 N 位的数字的计数

📅  最后修改于: 2021-09-22 10:40:55             🧑  作者: Mango

给定一个正整数N ,任务是计算可以用N位表示并设置了0位和N位的数字。

例子:

方法:超出给定的N个比特中,只有两个位需要被设置即0N位。因此,将这 2 位设置为 1,剩下的N – 2位可以是01,并且有2 N – 2种方法。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the count of n-bit
// numbers whose 0th and nth bits are set
int countNum(int n)
{
    if (n == 1)
        return 1;
    int count = pow(2, n - 2);
    return count;
}
 
// Driver code
int main()
{
    int n = 3;
    cout << countNum(n);
 
    return 0;
}


Java
// Java implementation of the approach
import java.io.*;
 
class GFG
{
    // Function to return the count of n-bit
    // numbers whose 0th and nth bits are set
    static int countNum(int n)
    {
        if (n == 1)
            return 1;
             
        int count = (int) Math.pow(2, n - 2);
        return count;
    }
     
    // Driver code
    public static void main (String[] args)
    {
        int n = 3;
        System.out.println(countNum(n));
    }
}
 
// This code is contributed by ajit


Python
# Python3 implementation of the approach
 
# Function to return the count of n-bit
# numbers whose 0th and nth bits are set
def countNum(n):
    if (n == 1):
        return 1
    count = pow(2, n - 2)
    return count
 
# Driver code
 
n = 3
print(countNum(n))
 
# This code is contributed by mohit kumar 29


C#
// C# implementation of the approach
using System;
 
class GFG
{
 
    // Function to return the count of n-bit
    // numbers whose 0th and nth bits are set
    static int countNum(int n)
    {
        if (n == 1)
            return 1;
             
        int count = (int) Math.Pow(2, n - 2);
        return count;
    }
     
    // Driver code
    static public void Main ()
    {
        int n = 3;
        Console.WriteLine(countNum(n));
    }
}
 
// This code is contributed by AnkitRai01


Javascript


输出:
2

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程