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 check if k'th bit is set for a given number or not.
Examples
Consider n = 20(00010100), k = 3
So, the result after turning off the 3rd bit => 00010000 & (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 − If obtained number is not 0 then Kth of n is set else not set.
Example
package main
import (
"fmt"
"strconv"
)
func CheckKthBitSet(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))
flag := CheckKthBitSet(n, k)
if flag !=0 {
fmt.Printf("%d rd bit of %d is aleady set.\n", k, n)
} else {
fmt.Printf("%d rd bit of %d is not set.\n", k, n)
}
}
Output
Binary of 20 is: 10100. 3 th bit of 20 is aleady set.
Advertisements
