Se da un número N. Necesitamos imprimir su ‘K’th Least Significant Bit .
Ejemplos:
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.
Podemos resolver fácilmente este problema siguiendo los siguientes pasos:
C++
// CPP code to print 'K'th LSB #include <bits/stdc++.h> 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
Python3
# 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
<?php // PHP code to print 'K'th LSB // Function returns 1 if set, 0 if not function LSB($num, $K) { return ($num & (1 << ($K - 1))); } // Driver code $num = 10; $K = 4; $r = LSB($num, $K); if($r) echo '1'; else echo '0'; // This code is contributed by Ajit ?>
Javascript
<script> // Javascript code to print 'K'th LSB // Function returns 1 if set, 0 if not function LSB(num, K) { let x = (num & (1 << (K-1))) != 0; return (x); } let num = 10, K = 4; //Function call if(LSB(num, K)) document.write("1") ; else document.write("0"); </script>
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA