Leetcode 258. Add Digits
題目的意思是給定一個非負整數,不斷地重複這個過程:將其每一位數字加起來求和。直到最終得到的結果僅有一位數字。不用迴圈或者遞迴能否實現時間複雜度為O(1)的做法?
方法1:寫了一個迴圈版本的。
class Solution {
public:
int add(int num)
{
int re=0;
while(num>0)
{
re+=num%10;
num/=10;
}
return re;
}
int addDigits(int num) {
while(true)
{
if (add(num)<10)
return add(num);
else
num=add(num);
}
return 0;
}
};
方法2:寫了一個遞迴版本的。
class Solution {
public:
int addDigits(int num) {
int re = 0;
while (num > 0)
{
re += num % 10;
num /= 10;
}
if (re < 10)
return re;
return addDigits(re);
}
};
不用迴圈或者遞迴能否實現時間複雜度為O(1)的做法。看了一下答案,這道題實際上是求給定數的樹根:a的數根b = ( a - 1) % 9 + 1。
class Solution {
public:
int addDigits(int num) {
return (num-1)%9+1;
}
};
相關文章
- [LeetCode] 258. Add DigitsLeetCodeGit
- 258. Add Digits--LeetCode RecordGitLeetCode
- Add Digits 各位相加Git
- LeetCode- Count Numbers with Unique DigitsLeetCodeGit
- [LeetCode] 402. Remove K DigitsLeetCodeREMGit
- Leetcode Add BinaryLeetCode
- Leetcode Add Two NumbersLeetCode
- LeetCode 2 Add Two NumbersLeetCode
- Leetcode 67 Add BinaryLeetCode
- LeetCode-Add and Search WordLeetCode
- LeetCode-Expression Add OperatorsLeetCodeExpress
- Leetcode-Add BinaryLeetCode
- Leetcode-Add Two NumbersLeetCode
- Add Binary Leetcode javaLeetCodeJava
- Add Two Numbers leetcode javaLeetCodeJava
- [LeetCode] 282. Expression Add OperatorsLeetCodeExpress
- LeetCode-2 Add Two NumbersLeetCode
- LeetCode 2. Add Two NumbersLeetCode
- LeetCode-Different Ways to Add ParenthesesLeetCode
- LeetCode OJ : 2 Add Two NumbersLeetCode
- Leetcode 415. Add StringsLeetCode
- [leetCode][016] Add Two NumbersLeetCode
- [Leetcode] 2. Add Two Numbers QuestionEditorial SolutionLeetCode
- LeetCode2: Add two numbers(兩數相加)LeetCode
- [LeetCode] Add Two Numbers 兩個數字相加LeetCode
- Fifth. LeetCode 2:Add Two Numbers 兩數之和LeetCode
- LeetCode 解題報告 - 2. Add Two NumbersLeetCode
- LeetCode67. Add Binary(二進位制加法)LeetCode
- 【LeetCode 67_字串_算術運算】Add BinaryLeetCode字串
- LeetCode解題報告 241. Different Ways to Add Parentheses [medium]LeetCode
- Codeforces 915C Permute DigitsGit
- ACL Beginner Contest E.Replace DigitsGit
- add exttrail 和add rmttail總結AI
- leetcode 兩數相加(add two numbers) Python程式設計實現LeetCodePython程式設計
- URAL 1658. Sum of Digits(簡單dp)Git
- Atcoder ARC090F Number of DigitsGit
- git add all和git add .區別Git
- jQuery add()jQuery