Consider two functions that accept as a parameter an unsigned integer and returns the number of digits of this number. One function is recursive and the other is non-recursive.
In terms of complexity , which implementation is better?
The language used is C/C++.
Here is non-recursive function:
int nbOfDigitsNR(int nb) {
int i=0
while(nb!=0){
nb=nb/10;
++i;
}
return i; // i is the number of digits
}
the recursive function:
int nbOfDigitsNR(int nb) {
static int i;
if (nb!=0){
i=i+1;
nbOfDigitsNR(nb/10);}
return i;
}
I suggest that the time complexity is the same: O(n), and the space complexity is different: O(n) recursive. O(1) non recursive.