美文网首页
Swift---LeetCode,第258题

Swift---LeetCode,第258题

作者: BabyNeedCare | 来源:发表于2021-11-26 15:07 被阅读0次

给定一个非负整数 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
    }

相关文章

网友评论

      本文标题:Swift---LeetCode,第258题

      本文链接:https://www.haomeiwen.com/subject/vmfxxrtx.html