📌  相关文章
📜  如何打开数字中的特定位?

📅  最后修改于: 2021-05-25 01:23:22             🧑  作者: Mango

给定一个数字n和一个值k,打开n中的第k位。
例子:

Input:  n = 4, k = 2
Output: 6

Input:  n = 3, k = 3
Output: 7

Input:  n = 64, k = 4
Output: 72

Input:  n = 64, k = 5
Output: 80

这个想法是使用按位<<和|运算符。使用表达式“(1 <<(k – 1))”,我们得到一个数字,除第k个比特外,所有其他比特都未设置。如果我们按位|用n表示此表达式,我们得到一个数字,除了第k个位数为1之外,所有位数均与n相同。
以下是上述想法的实现。

C++
// CPP program to turn on a particular bit
#include 
using namespace std;
 
// Returns a number that has all bits same as n
// except the k'th bit which is made 1
int turnOnK(int n, int k)
{
    // k must be greater than 0
    if (k <= 0)
        return n;
 
    // Do | of n with a number with all
    // unset bits except the k'th bit
    return (n | (1 << (k - 1)));
}
 
// Driver program to test above function
int main()
{
    int n = 4;
    int k = 2;
    cout << turnOnK(n, k);
    return 0;
}


Java
// Java program to turn on a particular
// bit
class GFG {
     
    // Returns a number that has all
    // bits same as n except the k'th
    // bit which is made 1
    static int turnOnK(int n, int k)
    {
         
        // k must be greater than 0
        if (k <= 0)
            return n;
     
        // Do | of n with a number with
        // all unset bits except the
        // k'th bit
        return (n | (1 << (k - 1)));
    }
     
    // Driver program to test above
    // function
    public static void main(String [] args)
    {
        int n = 4;
        int k = 2;
        System.out.print(turnOnK(n, k));
    }
}
 
// This code is contributed by Smitha


Python 3
# Python 3 program to turn on a
# particular bit
 
# Returns a number that has all
# bits same as n except the k'th
# bit which is made 1
def turnOnK(n, k):
 
    # k must be greater than 0
    if (k <= 0):
        return n
 
    # Do | of n with a number
    # with all unset bits except
    # the k'th bit
    return (n | (1 << (k - 1)))
 
# Driver program to test above
# function
n = 4
k = 2
print(turnOnK(n, k))
 
# This code is contributed by
# Smitha


C#
// C# program to turn on a particular
// bit
using System;
 
class GFG {
     
    // Returns a number that has all
    // bits same as n except the k'th
    // bit which is made 1
    static int turnOnK(int n, int k)
    {
         
        // k must be greater than 0
        if (k <= 0)
            return n;
     
        // Do | of n with a number
        // with all unset bits except
        // the k'th bit
        return (n | (1 << (k - 1)));
    }
     
    // Driver program to test above
    // function
    public static void Main()
    {
        int n = 4;
        int k = 2;
        Console.Write(turnOnK(n, k));
    }
}
 
// This code is contributed by Smitha


PHP


Javascript


输出:
6