2016-10-22 62 views

回答

2

這裏是一個可能實現:

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