- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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.
- Related Articles
- Golang Program to get the magnitude of the given number
- Golang program to delete the node after the Kth node.
- Golang Program to find the parity of a given number.
- Golang Program to update the node value after the Kth node.
- Golang Program to Print the Multiplication Table of a Given Number
- Program to find the kth factor of n using Python
- Golang Program to check the power of 4 of a given number
- Golang Program to insert a new node after the Kth node.
- Golang Program to Read a Number (n) and Compute (n+nn+nnn)
- Golang Program to count the number of flips to convert a given integer to another.
- Golang Program to check the given number is an odd number using library function
- Write a Golang program to find the factorial of a given number (Using Recursion)
- Write a Golang program to find the sum of digits for a given number
- Golang Program to Read a Number (n) and Print the Natural Numbers Summation Pattern
- Golang Program to Find the Sum of N Numbers using Recursion

Advertisements