LeetCode:Add Digits

本文介绍了一种高效的算法,用于计算任意非负整数的数字根,即反复加总该整数的所有位直到只剩一位数的过程。文章提供了一种不依赖循环或递归的O(1)运行时解决方案,并附带了简洁的C++实现代码。

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



问题描述:

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?

Hint:

Show Hint

  1. A naive implementation of the above process is trivial. Could you come up with other methods?Show More Hint
  2. What are all the possible results?Show More Hint
  3. How do they occur, periodically or randomly?Show More Hint
  4. You may find this Wikipedia article useful.

思路:

digit = num - 9 * ((n - 1) / 9)

参考自维基百科:https://en.wikipedia.org/wiki/Digital_root

代码:

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fullstack_lth

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值