📜  切换数字中除第k位以外的所有位。

📅  最后修改于: 2021-04-28 14:09:09             🧑  作者: Mango

给定一个正(或无符号)整数n ,编写一个函数来切换除第k位以外的所有位。在此,k的值从0(零)开始,从右开始。

例子

Input : n = 4294967295, k = 0
Output : 1
The number 4294967295 in 32 bits has all bits
set.  When we toggle all bits except last bit,
we get 1.

Input  :  n = 1, k = 1
Output : 4294967292
4294967262 has all bits toggled except second
bit from right.
  1. 在第k个位置切换位。我们通过找到一个仅设置第k位的数字(使用1 << k),然后对该数字n进行按位XOR来实现。
  2. 使用〜(按位取反)切换上面获得的数字的所有位
C++
// C++ program to toggle all bits except kth bit
#include 
using namespace std;
 
// Returns a number with all bit toggled in n
// except k-th bit
unsigned int toggleAllExceptK(unsigned int n,
                              unsigned int k)
{
     
    /* 1) Toggle k-th bit by doing n ^ (1 << k)
       2) Toggle all bits of the modified number */
    return ~(n ^ (1 << k));
}
 
// Driver code
int main()
{
    unsigned int n = 4294967295;
    unsigned int k = 0;
     
    cout << toggleAllExceptK(n, k);
     
    return 0;
}
 
// This code is contributed by khushboogoyal499


C
// C program to toggle all bits except kth bit
#include
 
// Returns a number with all bit toggled in n
// except k-th bit
unsigned int toggleAllExceptK(unsigned int n,
                            unsigned int k)
{
   /* 1) Toggle k-th bit by doing n ^ (1 << k)
      2) Toggle all bits of the modified number */
    return ~(n ^ (1 << k));
}
 
// Driver code
int main()
{
    unsigned int n = 4294967295;
    unsigned int k = 0;
    printf("%u", toggleAllExceptK( n, k));
    return 0;
}


Python3
# Python3 program to toggle all bits
# except kth bit
 
# Returns a number with all bit toggled
# in n except k-th bit
def toggleAllExceptK(n, k):
     
    # 1) Toggle k-th bit by doing n ^ (1 << k)
    # 2) Toggle all bits of the modified number
    temp = bin(n ^ (1 << k))[2:]
 
    ans = ""
 
    for i in temp:
        if i == '1':
            ans += '0'
        else:
            ans += '1'
 
    return int(ans, 2)
 
# Driver code
if __name__ == '__main__':
     
    n = 4294967295
    k = 0
     
    print(toggleAllExceptK(n, k))
 
# This code is contributed by mohit kumar 29


输出:

1