给定一个数字n和k(1<=k<=32),在n的二进制表示中找到第k位的值。位从右(最低有效位)到左(最高有效位)进行编号。
null
例如:
Input : n = 13, k = 2Output : 0Explanation:Binary representation of 13 is 1101.Second bit from right is 0.Input : n = 14, k = 3Output : 1Explanation:Binary representation of 14 is 1110.Third bit from right is 1.
方法: 1) 查找除第k位以外所有0的数字。我们使用(1< 2) 用n按位和以上获得的数字进行运算,以确定n中的第k位是否已设置。
以下是上述方法的实施情况:
C++
// CPP program to find k-th bit from right #include <bits/stdc++.h> 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
<?php // PHP program to find // k-th bit from right function printKthBit( $n , $k ) { echo ( $n & (1 << ( $k - 1))); } // Driver Code $n = 13; $k = 2; printKthBit( $n , $k ); // This code is contributed // by anuj_67. ?> |
Javascript
<script> // JavaScript program to find k-th bit from right function printKthBit(n, k) { document.write((n & (1 << (k - 1))) >> (k - 1)); } // Driver Code var n = 13, k = 2; // Function Call printKthBit(n, k); </script> |
输出:
0
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END