我想知道打印整数二进制表示的递归函数会在swift中看起来像什么?
答案 0 :(得分:3)
以下是一种可能的实施方式:
func toBinary(_ n: Int) -> String {
if n < 2 {
return "\(n)"
}
return toBinary(n / 2) + "\(n % 2)"
}
print(toBinary(11)) // "1011"
print(toBinary(170)) // "10101010"
注意:这不会处理负整数。
如果您确实希望该函数打印二进制文件而不是将其作为String
返回,则可以执行以下操作:
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