Golang 程式將整數轉換為二進位制表示


示例

例如,n = 1(1 的二進位制表示: 1)

例如,n = 5(5 的二進位制表示: 101)

例如,n = 20(20 的二進位制表示: 10100)

例如,n = 31(31 的二進位制表示: 11111)

解決此問題的途徑

步驟 1 − 定義一種接受整數 n 的方法。

步驟 2 − 使用 golang 程式包將 n 轉換為二進位制表示

步驟 3 − 返回轉換後的二進位制表示。

示例

 即時演示

package main
import (
   "fmt"
   "strconv"
)
func IntegerToBinary(n int) string {
   return strconv.FormatInt(int64(n), 2)
}
func main(){
   n := 1
   fmt.Printf("Binary Representation of %d is %s.\n", n, IntegerToBinary(n))
   n = 5
   fmt.Printf("Binary Representation of %d is %s.\n", n, IntegerToBinary(n))
   n = 20
   fmt.Printf("Binary Representation of %d is %s.\n", n, IntegerToBinary(n))
   n = 31
   fmt.Printf("Binary Representation of %d is %s.\n", n, IntegerToBinary(n))
}

輸出

Binary Representation of 1 is 1.
Binary Representation of 5 is 101.
Binary Representation of 20 is 10100.
Binary Representation of 31 is 11111.

更新時間:18-Mar-2021

3K+ 次瀏覽

開始您的 職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.