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 toggle the Kth of the given number n.
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 ^ (1k-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.
Advertisements
