给定一个数字n和一个值k。从右边开始,在n的二进制表示中设置第k位。LSB(或最后一位)的位置为0,最后一位的位置为1,依此类推。此外,0<=k
null
Input : n = 10, k = 2Output : 14(10)10 = (1010)2Now, set the 2nd bit from right.(14)10 = (1110)22nd bit has been set.Input : n = 15, k = 3Output : 153rd bit of 15 is already set.
要设置任何位,我们使用按位或|运算符。我们已经知道,如果操作数的任何对应位被设置(1),按位或|运算符将结果的每一位计算为1。为了设置一个数字的第k位,我们需要将其向左移位1k次,然后执行按位OR运算,并在之前执行左移位的数字和结果。
In general, (1 << k) | n.
C++
// C++ implementation to set the kth bit // of the given number #include <bits/stdc++.h> using namespace std; // function to set the kth bit int setKthBit( int n, int k) { // kth bit of n is being set by this operation return ((1 << k) | n); } // Driver program to test above int main() { int n = 10, k = 2; cout << "Kth bit set number = " << setKthBit(n, k); return 0; } |
JAVA
// Java implementation to set the kth bit // of the given number class GFG { // function to set the kth bit static int setKthBit( int n, int k) { // kth bit of n is being set by this operation return (( 1 << k) | n); } // Driver code public static void main(String arg[]) { int n = 10 , k = 2 ; System.out.print( "Kth bit set number = " + setKthBit(n, k)); } } // This code is contributed by Anant Agarwal. |
Python3
# Python implementation # to set the kth bit # of the given number # function to set # the kth bit def setKthBit(n,k): # kth bit of n is being # set by this operation return (( 1 << k) | n) # Driver code n = 10 k = 2 print ( "Kth bit set number = " , setKthBit(n, k)) # This code is contributed # by Anant Agarwal. |
C#
// C# implementation to set the // kth bit of the given number using System; class GFG { // function to set the kth bit static int setKthBit( int n, int k) { // kth bit of n is being set // by this operation return ((1 << k) | n); } // Driver code public static void Main() { int n = 10, k = 2; Console.Write( "Kth bit set number = " + setKthBit(n, k)); } } // This code is contributed by // Smitha Dinesh Semwal. |
PHP
<?php // PHP implementation to // set the kth bit of // the given number // function to set // the kth bit function setKthBit( $n , $k ) { // kth bit of n is being // set by this operation return ((1 << $k ) | $n ); } // Driver Code $n = 10; $k = 2; echo "Kth bit set number = " , setKthBit( $n , $k ); // This code is contributed by m_kit ?> |
Javascript
<script> // Javascript implementation to set the // kth bit of the given number // function to set the kth bit function setKthBit(n, k) { // kth bit of n is being set // by this operation return ((1 << k) | n); } let n = 10, k = 2; document.write( "Kth bit set number = " + setKthBit(n, k)); // This code is contributed by rameshtravel07. </script> |
输出:
Kth bit set number = 14
本文由 阿尤什·焦哈里 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END