Golang程序 将一个整数转换成二进制表示法

例子

例如,n = 1 (1的二进制表示法:1)

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

例如,n = 20 (5的二进制表示法:10100)

例如,n=31(31的二进制表示:111111)。

解决这个问题的方法

第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.