[java] Add Digits 数字相加

本文介绍了一道LeetCode经典题目“加位数”的解决方案。该题要求反复累加给定非负整数的各个位数直到结果仅剩一位,并提出在O(1)时间复杂度且不使用循环或递归的挑战。文章通过观察规律,得出简洁高效的公式化解答。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

leetcode 原题链接: https://leetcode.com/problems/add-digits/

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?

简要翻译:

给定一个非零整数num,重复将各位上的数进行求和,知道结果只有一个数字位置。

例如,给定数字38,运行结果为 3+8 = 11, 1+1 = 2. 因为2只有一个数字,所以返回2.。

要求:在没有循环和递归的帮助下,在O(1)的运行时间内完成计算。

简要分析:

题目中要求,不使用循环和递归的前提下,解决这个问题。

根据已有的经验,于是我写出了如下的代码:

public static int addDigits(int num) 
	{
		num = sumDigits(num);
		if (num < 10)
			return num;
		else
			return addDigits(num);
    }
	private static int sumDigits(int num)
	{
		if (num < 10)
			return num;
		else
			return sumDigits(num/10)+num%10;
	}
这个代码 AC了的。不过我仔细一下, 不对啊!!! 这里我使用了递归啊。

因此虽然AC了 ,但是实际上这是不对的。

还需另想办法来解决这个问题。
那我们就试试几个数,试着找一下规律。。。

输入:1,2,3,4,5,6,7,8,9,10     11, 12, 13, 14, 15, 16, 17, 18, 19,20

结果:1, 2,3,4,5,6,7,8,9,1,      2,  3,    4,    5,    6, ,7, 8, 9, 1, 2

根据上面的尝试,我们可以发现,这里是有规律的。

即结果满足,(num-1)%9+1

因此有了如下代码:

public static int addDigits(int num) 
	{
	    return (num-1)%9+1;
    }

这个答案才是AC过的正确答案!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值