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