LeetCode 258 Add Digits(数字相加,数字根)
LeetCode 数字 add 相加 digits
2023-09-11 14:20:45 时间
翻译
给定一个非负整型数字,反复相加其全部的数字直到最后的结果仅仅有一位数。
比如:
给定sum = 38,这个过程就像是:3 + 8 = 11。1 + 1 = 2。由于2仅仅有一位数。所以返回它。
紧接着:
你能够不用循环或递归在O(1)时间内完毕它吗?
原文
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?
分析
事实上我并不会写,循环和递归都不能用……我还能怎么办呐。
然后看了LeetCode上给的提示。看了维基百科的一篇文章:Digital root。
有了这个的话,就非常easy了。详细这个公式的细节,大家自己參看维基吧,由于篇幅过长就不翻译了。
代码
class Solution {
public:
int floor(int x) {
return (x - 1) / 9;
}
int addDigits(int num) {
return num - 9 * floor(num);
}
};
相关文章
- 【LeetCode-面试算法经典-Java实现】【129-Sum Root to Leaf Numbers(全部根到叶子结点组组成的数字相加)】
- LeetCode高频题66. 加一,给你一个数组表示数字,则加1返回结果
- LeetCode高频题:int数字x被拆为p1,p2,p3,输入N必须满足N=p1+p2/p3,p2/p3整除,N有多少种分数形式
- 【删除指定数字——leetcode]
- 2021.10 LeetCode每日一题(10.01-10.15)
- 每日leetcode算法题:2042检查句子中的数字是否递增
- 团灭LeetCode跳跃游戏(相关话题:贪心,BFS)
- 183、【动态规划】leetcode ——516. 最长回文子序列(C++版本)
- 145、【动态规划】leetcode ——70. 爬楼梯:暴力法+动态规划(C++版本)
- 【LeetCode】145. Binary Tree Postorder Traversal (3 solutions)
- [LeetCode] 1323. Maximum 69 Number 6和9组成的最大数字
- [LeetCode] 1185. Day of the Week 一周中的第几天
- [LeetCode] 829. Consecutive Numbers Sum 连续数字之和
- [LeetCode] Largest Number At Least Twice of Others 至少是其他数字两倍的最大数
- [LeetCode] 568. Maximum Vacation Days 最大化休假日
- [LeetCode] Find All Numbers Disappeared in an Array 找出数组中所有消失的数字
- [LeetCode] Reconstruct Original Digits from English 从英文中重建数字
- [LeetCode] 380. Insert Delete GetRandom O(1) 常数时间内插入删除和获得随机数
- [LeetCode] Consecutive Numbers 连续的数字
- [LeetCode] 260. Single Number III 单独的数字之三
- [LeetCode] 215. Kth Largest Element in an Array 数组中第k大的数字
- [LeetCode] 137. Single Number II 单独的数字之二
- [LeetCode] 2. Add Two Numbers 两个数字相加