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.
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP