切换数字的第k位

对于给定的数字n,如果第k位为0,则将其切换为1,如果为1,则将其切换为0。 例如:

null
Input : n = 5, k = 1Output : 45 is represented as 101 in binaryand has its first bit 1, so toggling it will result in 100 i.e. 4.Input : n = 2, k = 3Output : 6Input : n = 75, k = 4Output : 67

下面是查找第k位值的简单步骤

1) Left shift given number 1 by k-1 to create    a number that has only set bit as k-th bit.    temp = 1 << (k-1)2) Return bitwise XOR of temp and n.  Since temp   has only k-th bit set, doing XOR would toggle    only this bit.

例子:

 n = 75 and k = 4 temp = 1 << (k-1) = 1 << 3 = 8  Binary Representation of temp = 0..00001000  Binary Representation of n = 0..01001011  Bitwise XOR of two numbers = 0..01000011

C++

// CPP program to toggle k-th bit of n
#include<iostream>
using namespace std;
int toggleKthBit( int n, int k)
{
return (n ^ (1 << (k-1)));
}
// Driver code
int main()
{
int n = 5, k = 1;
cout << toggleKthBit(n , k);
return 0;
}


JAVA

// Java program to toggle
// k-th bit of a number
class Toggle
{
static int toggleKthBit( int n, int k)
{
return (n ^ ( 1 << (k- 1 )));
}
// main function
public static void main (String[] args)
{
int n = 5 , k = 1 ;
System.out.println(toggleKthBit(n , k));
}
}


Python3

# Python3 code to toggle k-th bit of n
def toggleKthBit(n, k):
return (n ^ ( 1 << (k - 1 )))
# Driver code
n = 5
k = 1
print ( toggleKthBit(n , k))
# This code is contributed by "Sharad_Bhardwaj".


C#

// C# program to toggle
// k-th bit of a number
using System;
class GFG {
static int toggleKthBit( int n, int k)
{
return (n ^ (1 << (k-1)));
}
// main function
public static void Main()
{
int n = 5, k = 1;
Console.WriteLine(toggleKthBit(n , k));
}
}
//This code is contributed by Anant Agarwal.


PHP

<?php
// Php program to toggle k-th bit of n
function toggleKthBit( $n , $k )
{
return ( $n ^ (1 << ( $k - 1)));
}
// Driver code
$n = 5;
$k = 1;
echo toggleKthBit( $n , $k );
// This code is contributed by Ajit
?>


Javascript

<script>
// Javascript program to toggle
// k-th bit of a number
function toggleKthBit(n, k)
{
return (n ^ (1 << (k-1)));
}
let n = 5, k = 1;
document.write(toggleKthBit(n , k));
</script>


输出:

4

本文由 萨希·提瓦里 .如果你喜欢极客(我们知道你喜欢!)如果你想投稿,你也可以用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享