📜  设置给定数字的第K位

📅  最后修改于: 2021-04-29 18:17:15             🧑  作者: Mango

给定数字n和值k。从右边,在n的二进制表示形式中设置第k位。 LSB(或最后一位)的位置为0,倒数第二位为1,依此类推。同样,0 <= k

例子:

Input : n = 10, k = 2
Output : 14
(10)10 = (1010)2
Now, set the 2nd bit from right.
(14)10 = (1110)2
2nd bit has been set.

Input : n = 15, k = 3
Output : 15
3rd bit of 15 is already set.

要设置任何位,我们使用按位“或” |运算符。我们已经知道按位OR |运算符评估结果为1的每个比特,如果任何操作数的相应位被置(1)。为了设置数字的第k位,我们需要向左移动1 k次,然后对数字进行按位或运算,并在此之前执行左移结果。

In general, (1 << k) | n.
C++
// C++ implementation to set the kth bit
// of the given number
#include 
  
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


输出:

Kth bit set number = 14