Golang Program to turn on the k’th bit in a number.

Go ProgrammingServer Side ProgrammingProgramming

Example

For example consider n = 20(00010100), k = 4.
So result after turning on 4th bit => 00010000 | (1 << (4-1))

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 obtained number.

Example

package main
import (
   "fmt"
   "strconv"
)
func TurnOnKthBit(n, k int) int {
   return n | (1 << (k-1))
}
func main(){
   var n = 20
   var k = 4
   fmt.Printf("Binary of %d is: %s.\n", n, strconv.FormatInt(int64(n), 2))
   newNumber := TurnOnKthBit(n, k)
   fmt.Printf("After turning on %d th 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 on 4 th bit of 20 is: 28.
Binary of 28 is: 11100.
raja
Updated on 17-Mar-2021 10:56:25

Advertisements