Golang Program to toggle the Kth of the given number n.

Go ProgrammingServer Side ProgrammingProgramming

Examples

Consider n = 20(00010100), k = 3.

After toggling the kth bit of the given number: 00010000 => 16.

Approach to solve this problem

Step 1 − Define a method, where n and k would be the arguments, returns type is int.

Step 2 − Perform AND operation with n ^ (1<<(k-1)).

Step 3 − Return the number after operation.

Example

package main
import (
   "fmt"
   "strconv"
)
func ToggleKthBit(n, k int) int {
   return n ^ (1 << (k-1))
}
func main(){
   var n = 20
   var k = 3
   fmt.Printf("Binary of %d is: %s.\n", n, strconv.FormatInt(int64(n), 2))
   number := ToggleKthBit(n, k)
   fmt.Printf("After toggling %d rd bit of the given number is %d.\n", k, number)
}

Output

Binary of 20 is: 10100.
After toggling 3 rd bit of the given number is 16.
raja
Published on 17-Mar-2021 10:59:42
Advertisements