I have the following code, which is an answer to this question: https://leetcode.com/problems/add-digits/
class Solution {
public:
int addDigits(int num) {
if (!num/10)
return num;
long d = 1;
int retVal = 0;
while(num / d){
d *= 10;
}
for(d; d >= 1; d/=10){
retVal += num / d;
num %= d;
}
if (retVal > 9)
retVal = addDigits(retVal);
return retVal;
}
};
As a follow-up to this though, I'm trying to determine what the BigO growth is. My first attempt at calculating it came out to be O(n^n)
(I assumed since the growth of each depth is directly depended on n
every time), which is just depressing. Am I wrong? I hope I'm wrong.
Looks like it's
O(1)
for values < 10, andO(n)
for any other values.I'm not well versed enough with the Big-O notation, to give an answer how this would be combined.
Most probably the first part is neclectable in significance, and such the overall time complexity becomes
O(n)
.In this case it's linear
O(n)
because you calladdDigits
method recursively without any loop and whatnot once in the method bodyMore details: Determining complexity for recursive functions (Big O notation)
Update: It's linear from the point of view of that the recursive function is called once. However, in this case, it's not exactly true, because the number of executions barely depends on input parameter.
Let
n
be the number of digits in base 10 ofnum
. I'd say thatWhich gives us
But can we do better? Note than the maximum number representable with 2 digits is
99
which reduce in this way99
->18
->9
.Note that we can always collapse 10 digits into 2
9999999999->90
. Forn>10
we can decompose than number inn/10
segments of up to 10 digits each and reduce those segments in numbers of 2 digits each to be summed. The sum ofn/10
numbers of 2 digits will always have less (or equal) than(n/10)*2
digits. ThereforeOther base cases with n<10 should be easier. This gives
Solving the recurrence equation gives