【LeetCode从零单刷】Add Digits

来源:互联网 发布:面纱3.0完美数据 编辑:程序博客网 时间:2024/05/22 14:06

题目:

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.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

解答:

从头开始写,就会慢慢发现规律。是以 9 个数循环出现:1,2,3,……9,10,11,……对应的结果是1,2,3,……9,1,2,……

具体分析以及公式可见维基百科:Digital Root

class Solution {public:    int addDigits(int num) {        return (num - 1) % 9 + 1;    }};

这里使用了一个小技巧:如果使用模9之后的余数来作为答案,那么9%9=0就是错误的。用 (num - 1)%9 + 1 来替代。以退为进

0 0
原创粉丝点击