Golang 程序用于计算将给定的整数转换为另一整数所需的翻转次数。
示例
考虑两个数字 m = 65 => 01000001 和 n = 80 => 01010000
翻转的比特数为 2。
解决此问题的步骤
步骤 1 - 将两个数字都转换为比特。
步骤 2 - 统计翻转的比特数。
示例
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))
}输出
Binary of 65 is: 1000001. Binary of 80 is: 1010000. The number of bits flipped is 2
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP