Swift---LeetCode,第258题

2021-11-26  本文已影响0人  BabyNeedCare

给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。

示例:

输入: 38
输出: 2
解释: 各位相加的过程为:3 + 8 = 11, 1 + 1 = 2。 由于 2 是一位数,所以返回 2。

    func addDigits(_ num: Int) -> Int {
        
        var firstValue = num

        while firstValue >= 10 {
            
            var total = 0
            
            "\(firstValue)".map { Int(String($0)) ?? 0 }.forEach { total += $0 }
            
            firstValue = total
        }
        
        return firstValue
    }
上一篇 下一篇

猜你喜欢

热点阅读