Swift 打印整数二进制表示形式的快速递归函数
我想知道打印整数二进制表示的递归函数在swift中会是什么样子?下面是一个可能的实现:Swift 打印整数二进制表示形式的快速递归函数,swift,function,recursion,binary,Swift,Function,Recursion,Binary,我想知道打印整数二进制表示的递归函数在swift中会是什么样子?下面是一个可能的实现: func toBinary(_ n: Int) -> String { if n < 2 { return "\(n)" } return toBinary(n / 2) + "\(n % 2)" } print(toBinary(11)) // "1011" print(toBinary(170)) // "10101010" 输出: func p
func toBinary(_ n: Int) -> String {
if n < 2 {
return "\(n)"
}
return toBinary(n / 2) + "\(n % 2)"
}
print(toBinary(11)) // "1011"
print(toBinary(170)) // "10101010"
输出:
func printBinary(_ n: Int, terminator: String = "\n") {
if n < 2 {
print(n, terminator: terminator)
}
else {
printBinary(n / 2, terminator: "")
print(n % 2, terminator: terminator)
}
}
printBinary(11)
printBinary(170)
printBinary(23, terminator: "")
print(" is the representation of 23 in binary")
1011
10101010
10111 is the representation of 23 in binary