[Swift] Add Digits

January 02, 2017 0 Comments

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 111 + 1 = 2. Since 2 has only one digit, return it.

把數字轉成文字然後拆開,遞迴相加後直到剩一個字元
--------------------

func addDigits(_ nums: Int) -> Int {
    
    var numsChar = String(nums).characters
    while (numsChar.count > 1){
        var sum = 0
        for char in numsChar {
            let intchar = String(char)
            sum = sum + Int(intchar)!
        }
        numsChar = String(sum).characters
    }
    return Int(String(numsChar))!

}

0 comments: