![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ^ (1<<(k-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