给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。
示例:
输入: 38 输出: 2 解释: 各位相加的过程为:3 + 8 = 11, 1 + 1 = 2。 由于 2 是一位数,所以返回 2。
进阶:
你可以不使用循环或者递归,且在 O(1) 时间复杂度内解决这个问题吗?
思路:
class Solution { func addDigits(_ num: Int) -> Int { if (num < 10) { return num; } let result = num % 9; if (result == 0) { return 9; } return result; } }
备注:
原数: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 数根: 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3
观察规律:每9个一循环 求树根数学公式 (x - 1) % 9 + 1