将一个数的各位数字加起来求和

一段十分简单的代码的背后常常对应的是一个完备的算法,否则代码不仅会显得臃肿和繁琐,而且非常容易出错。

功能需求

首先看看这段代码需要实现怎样的功能:

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 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

Follow up:

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

我们的代码如果只是按照传统的循环和递归方式去做的话,不仅增加算法的复杂度,而且也容易出错。为了提高运行的效率,我们需要先研究下这背后所蕴含的算法逻辑。

算法逻辑

The digital root (also repeated digital sum) of a non-negative integer is the (single digit) value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached.

For example, the digital root of 65,536 is 7, because 6 + 5 + 5 + 3 + 6 = 25 and 2 + 5 = 7.

Digital roots can be calculated with congruences in modular arithmetic rather than by adding up all the digits, a procedure that can save time in the case of very large numbers.

Digital roots can be used as a sort of checksum. For example, since the digital root of a sum is always equal to the digital root of the sum of the summands' digital roots.[needs copy edit] A person adding long columns of large numbers will often find it reassuring to apply casting out nines to his result—knowing that this technique will catch the majority of errors.

Digital roots are used in Western numerology, but certain numbers deemed to have occult significance (such as 11 and 22) are not always completely reduced to a single digit.

The number of times the digits must be summed to reach the digital sum is called a number's additive persistence; in the above example, the additive persistence of 65,536 is 2.

It helps to see the digital root of a positive integer as the position it holds with respect to the largest multiple of 9 less than it. For example, the digital root of 11 is 2, which means that 11 is the second number after 9. Likewise, the digital root of 2035 is 1, which means that 2035 − 1 is a multiple of 9. If a number produces a digital root of exactly 9, then the number is a multiple of 9.

代码实现

搞清楚这套逻辑之后,即可以简单的代码进行实现了。而不必真的将一个数的每一位进行相加的操作了。

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

转载于:https://my.oschina.net/donngchao/blog/547924

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值