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

更新於: 17-Mar-2021

102 檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.