试图在Swift中将二进制数转换为基数为10的数字

时间:2016-09-07 03:50:31

标签: swift

我是Swift的新手,并且在开始编程时没有多少经验,我编写了这段代码的目的是将二进制输入转换为基数10输出。任何人都可以告诉我故障的位置并解释如何正确地做到这一点?非常感激。

func toBaseTen(baseTwo: String) -> String{
    let reversed = String(baseTwo.characters.reverse()) //cast to String or else returns a ReverseCollection
    let toArray = reversed.characters.map { String($0) }
    var finalString = [String]()
    for element in toArray {
        let exponent = Double(toArray.indexOf(element)!)
        let elementToBeAdded = { String(pow(Double(element)!, exponent)) }
        if element == "1" {
            finalString.append(elementToBeAdded())
        }
    }
    finalString.reduce("", combine: +)
    return String(finalString)

}

0 个答案:

没有答案