Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 打印整数二进制表示形式的快速递归函数_Swift_Function_Recursion_Binary - Fatal编程技术网

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

我想知道打印整数二进制表示的递归函数在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 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