- 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 count the number of flips to convert a given integer to another.
Examples
Consider two numbers m = 65 => 01000001 and n = 80 => 01010000
Number of bits flipped is 2.
Approach to solve this problem
Step 1 − Convert both numbers into bits.
Step 2 − Count number of bits are flipped.
Example
package main import ( "fmt" "strconv" ) func FindBits(x, y int) int{ n := x ^ y count := 0 for ;n!=0; count++{ n = n & (n-1) } return count } func main(){ x := 65 y := 80 fmt.Printf("Binary of %d is: %s.\n", x, strconv.FormatInt(int64(x), 2)) fmt.Printf("Binary of %d is: %s.\n", y, strconv.FormatInt(int64(y), 2)) fmt.Printf("The number of bits flipped is %d\n", FindBits(x, y)) }
Output
Binary of 65 is: 1000001. Binary of 80 is: 1010000. The number of bits flipped is 2
Advertisements