给出了数字N。我们需要打印其“ K”个最低有效位。
例子 :
Input : num = 10, k = 4
Output : 1
Explanation : Binary Representation
of 10 is 1010. 4th LSB is 1.
Input : num = 16, k = 3
Output : 0
Explanation : Binary Representation
of 16 is 10000. 3rd LSB is 0.
我们可以通过以下步骤轻松解决此问题:
- 向左移动数字“ 1”(K-1)次。
- 这将产生一个数字,除了第K个比特外,所有其他未设置的比特。现在,我们将对给定数字对移位后的数字进行逻辑“与”运算。
- 除第“ K”位以外的所有位都将产生0,而“ K”位将取决于数字。这是因为1 AND 1为1。0AND 1为0。
C++
// CPP code to print 'K'th LSB
#include
using namespace std;
//Function returns 1 if set, 0 if not
bool LSB(int num, int K)
{
return (num & (1 << (K-1)));
}
//Driver code
int main()
{
int num = 10, K = 4;
//Function call
cout << LSB(num, K);
return 0;
}
java
// java code to print 'K'th LSB
import java .io.*;
class GFG {
// Function returns 1 if set, 0 if not
static boolean LSB(int num, int K)
{
boolean x = (num & (1 << (K-1))) != 0;
return (x);
}
// Driver code
public static void main(String[] args)
{
int num = 10, K = 4;
//Function call
if(LSB(num, K))
System.out.println("1") ;
else
System.out.println("0");
}
}
// This code is contributed by Anuj_67
Python
# Python code to print 'K'th LSB
# Function returns 1 if set, 0 if not
def LSB(num, K):
return bool(num & (1 << (K - 1) ))
# Driver code
num, k = 10, 4
res = LSB(num, k)
if res :
print 1
else:
print 0
#This code is contributed by Sachin Bisht
C#
// C# code to print 'K'th LSB
using System;
class GFG {
// Function returns 1 if set, 0 if not
static bool LSB(int num, int K)
{
bool x = (num & (1 << (K-1))) != 0;
return (x);
}
// Driver code
static void Main()
{
int num = 10, K = 4;
//Function call
if(LSB(num, K))
Console.Write("1") ;
else
Console.Write("0");
}
}
// This code is contributed by Anuj_67
PHP
Javascript
输出 :
1