📜  在二进制表示中找到第k位的值

📅  最后修改于: 2021-05-25 08:25:04             🧑  作者: Mango

给定数字n和k(1 <= k <= 32),在n的二进制表示形式中找到第k位的值。位从右(最低有效位)到左(最高有效位)编号。

例子 :

Input :  
n = 13, k = 2
Output : 
0
Explanation:
Binary representation of 13 is 1101.
Second bit from right is 0.

Input :  
n = 14, k = 3
Output : 
1
Explanation:
Binary representation of 14 is 1110.
Third bit from right is 1.

方法:
1)查找除第k个位置以外全为0的数字。我们使用(1 <<(k-1))得到这个数字。例如,如果k = 3,则(1 << 2)给出(00..00100)。
2)用n进行按位求和并用n求出大于n的值,以查找n中的第k位是否被置位。

下面是上述方法的实现:

C++
// CPP program to find k-th bit from right
#include 
using namespace std;
 
void printKthBit(unsigned int n, unsigned int k)
{
    cout << ((n & (1 << (k - 1))) >> (k - 1));
}
 
// Driver Code
int main()
{
    unsigned int n = 13, k = 2;
   
    // Function Call
    printKthBit(n, k);
    return 0;
}


Java
// Java program to find
// k-th bit from right
import java.io.*;
 
class GFG {
    static void printKthBit(long n, long k)
    {
        System.out.println(
            ((n & (1 << (k - 1))) >> (k - 1)));
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        long n = 13, k = 2;
       
        // Function Call
        printKthBit(n, k);
    }
}
 
// This code is contributed by anuj_67.


Python3
# Python 3 program to find
# k-th bit from right
 
def printKthBit(n, k):
 
    print((n & (1 << (k - 1))) >> (k - 1))
 
# Driver Code
n = 13
k = 2
 
# Function Call
printKthBit(n, k)
 
# This code is contributed by Smitha


C#
// C# program to find k-th bit from right
using System;
 
class GFG {
 
    static void printKthBit(long n, long k)
    {
        Console.WriteLine((n & (1 << (k - 1))) >> (k - 1));
    }
 
    // Driver Code
    public static void Main()
    {
        long n = 13, k = 2;
         
        // Function Call
        printKthBit(n, k);
    }
}
 
// This code is contributed by anuj_67.


PHP


输出 :
0