A number N is given. We need to print its ‘K’th Least Significant Bit.
Examples :
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.
We can easily solve this problem by following steps :
- Shift the number ‘1’ (K-1) times left.
- This will yield a number with all unset bits but the ‘K’th bit. Now, we’ll perform logical AND of the shifted number with given number.
- All bits except the ‘K’th bit will yield 0, and ‘K’th bit will depend on the number. This is because, 1 AND 1 is 1. 0 AND 1 is 0.
C++
#include <bits/stdc++.h>
using namespace std;
bool LSB( int num, int K)
{
return (num & (1 << (K-1)));
}
int main()
{
int num = 10, K = 4;
cout << LSB(num, K);
return 0;
}
|
java
import java .io.*;
class GFG {
static boolean LSB( int num, int K)
{
boolean x = (num & ( 1 << (K- 1 ))) != 0 ;
return (x);
}
public static void main(String[] args)
{
int num = 10 , K = 4 ;
if (LSB(num, K))
System.out.println( "1" ) ;
else
System.out.println( "0" );
}
}
|
Python3
def LSB(num, K):
return bool (num & ( 1 << (K - 1 ) ))
num, k = 10 , 4
res = LSB(num, k)
if res :
print ( 1 )
else :
print ( 0 )
|
C#
using System;
class GFG {
static bool LSB( int num, int K)
{
bool x = (num & (1 << (K-1))) != 0;
return (x);
}
static void Main()
{
int num = 10, K = 4;
if (LSB(num, K))
Console.Write( "1" ) ;
else
Console.Write( "0" );
}
}
|
PHP
<?php
function LSB( $num , $K )
{
return ( $num & (1 << ( $K - 1)));
}
$num = 10;
$K = 4;
$r = LSB( $num , $K );
if ( $r )
echo '1' ;
else
echo '0' ;
?>
|
Javascript
<script>
function LSB(num, K)
{
let x = (num & (1 << (K-1))) != 0;
return (x);
}
let num = 10, K = 4;
if (LSB(num, K))
document.write( "1" ) ;
else
document.write( "0" );
</script>
|
Output :
1
Time Complexity: O(1)
Auxiliary Space: O(1)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!