给定一个正(或无符号)整数 N ,编写一个函数来切换除第k位以外的所有位。这里k的值从0(零)开始,从右边开始。
null
例子 :
Input : n = 4294967295, k = 0Output : 1The number 4294967295 in 32 bits has all bitsset. When we toggle all bits except last bit,we get 1.Input : n = 1, k = 1Output : 42949672924294967262 has all bits toggled except secondbit from right.
- 在第k个位置切换位。我们通过找到一个只有第k位的数字(使用1<
- 使用~( 位反运算 )
C++
// C++ program to toggle all bits except kth bit #include <iostream> 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<stdio.h> // 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 |
Javascript
<script> // javascript program to toggle all bits except kth bit // Returns a number with all bit toggled in n // except k-th bit function toggleAllExceptK(n,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 let n = 4294967295; let k = 0; document.write(toggleAllExceptK(n, k)); //This code is contributed by unknown2108 </script> |
输出:
1
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END