您的位置:首页 > 其它

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

2015-12-19 00:00 375 查看
摘要: 将一个数的各位数字加起来求和

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

功能需求

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

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);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息