Golang program to turn off the k’th bit in a number.


Example

Consider n = 20(00010100), k = 3
The result after turning off the 3rd bit => 00010000 & ^(1<<(3-1)) => 00010000 & ^(1 << 2) =>
00010000 => 16s

Approach to solve this problem

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

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

Step 3 − Return the obtained number.

Example

package main
import (
   "fmt"
   "strconv"
)
func TurnOffKthBit(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))
   newNumber := TurnOffKthBit(n, k)
   fmt.Printf("After turning off %d rd bit of %d is: %d.\n", k, n, newNumber)
   fmt.Printf("Binary of %d is: %s.\n", newNumber, strconv.FormatInt(int64(newNumber), 2))
}

Output

Binary of 20 is: 10100.
After turning off 3 rd bit of 20 is 16.
Binary of 16 is: 10000.

Updated on: 17-Mar-2021

100 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements