Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Golang Program to turn on the k'th bit in a number.
Example
For example consider n = 20(00010100), k = 4. So result after turning on 4<sup>th</sup> 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
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.
Advertisements
