Golang 将整数转换为二进制表示的程序!
例子
例如,n=1(1:1的二进制表示)
例如,n=5(5的二进制表示:101)
例如,n=20(5的二进制表示: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.
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短