java数字位数求和_数值的每位数相加最终返回各位数 Add Digits

该博客讨论了如何在Java中求一个非负整数的数字位数之和,直到结果只剩一位数。提供了三种解决方案,包括循环相加法和基于数字规律的优化方法,其中优化后的解法能在O(1)时间内完成,并且代码执行时间更短。
摘要由CSDN通过智能技术生成

题目:

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?

解决:

① 将每位数相加,直到它们的和为个位数为止。耗时3ms。

public class Solution {

public int addDigits(int num) {

while(num > 9){

int sum = 0;

while(num > 0){

sum += (num % 10);

num /= 10;

}

num = sum;

}

return num;

}

}

②我们先来观察1到20的所有的树根:

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

根据上面的列举,我们可以得出规律,每9个一循环,所有大于9的数的树根都是对9取余,那么对于等于9的数对9取余就是0了,为了得到其本身,而且同样也要对大于9的数适用,我们就用(n-1)%9+1这个表达式来包括所有的情况,所以解法如下,耗时2ms:

public class Solution {

public int addDigits(int num) {

if (num <= 9) {

return num;

}

return (num -1) % 9 + 1;

}

}

③ 同一个思路

public class Solution {

public int addDigits(int num) {

return num % 9 == 0 ? (num == 0 ? 0 : 9) : num % 9;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值