258. Add Digits

本文介绍了计算一个非负整数的数根的两种方法。一种是通过循环不断地将数字的各位相加直至得到一位数;另一种是利用数学规律,通过简单的公式计算得出结果,实现O(1)的时间复杂度。

 

Given a non-negative integernum, repeatedly add all its digits until the result has only one digit.

For example:

Givennum = 38, the process is like:3 + 8 = 11,1 + 1 = 2. Since2has only one digit, return it.

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

题目让求各个数位的和,直到和小于10为止,

方法一

直观的想法就是直接相加,先想一下如何求各数位的和

while(num != 0)
{
	tmp += num % 10;
	num /= 10;
}
 
下面是完整代码
class Solution {
    public int addDigits(int num) {
        
        
        while(num / 10 > 0)
        {   int sum = 0;   ////注意定义变量的位置
            while(num != 0)
            {
                sum += num % 10;
                num /= 10;
            }
            num = sum;
        }
        return num;
    }
}
 
方法二
题目中说了不使用循环且时间复杂度为o(1),可以猜测必定有某种规律, 题目是Add Digits,实际上这在数学上面被称为 数根 ,先看下面例子:
1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8    
9    9    
10    1
11    2
12    3    
13    4
14    5
15    6
16    7
17    8
18    9
19    1
20    2
 
这20个数的数根有循环,且循环周期为9,循环的计算公式为(n-1)%  + 1,所以该题目i可以使用一行代码搞定
class Solution {
public:
    int addDigits(int num) {
        return (num - 1) % 9 + 1;  //周期第一位为1,若为2 则 + 2
    }
};
 
 

<wiz_tmp_tag id="wiz-table-range-border" contenteditable="false" style="display: none;">

 
 
 
 

转载于:https://www.cnblogs.com/wxshi/p/7598531.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值