-3
我想知道什麼會打印整數的二進制表示的遞歸函數看起來像在swift中?快速遞歸函數,打印一個整數的二進制表示
我想知道什麼會打印整數的二進制表示的遞歸函數看起來像在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"
注:這不處理負整數。
如果你真的想要的功能打印,而不是返回它作爲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