Hey Programmers,
Is there any better way to write the below recusive functions, plz help me so i can improve my programming...
1-
Write a recursive function that takes a nonnegitive integer and returns the sum of its digits,
int DigitSum(int n){
if(n == 0){
return 0;
}else{
return (n%10) + DigitSum(n/10);
}
}
2-
Write a recursive function DigitalRoot(int n) that returns the digital root of its arguments.
int DigitSum(int n){
if(n == 0){
return 0;
}else{
return (n%10) + DigitSum(n/10);
}
}
int DigitRoot(int n){
if((n/10) < 1){
return n;
}else{
return DigitRoot(DigitSum(n));
}
}
3- Reverse string
string Reverse(string str){
if(str.length()==1){
return str;
}else{
return str[str.length()-1] + Reverse(str.substr(0,str.length()-1));
}
}
4-
write a recursive function to convert integer into string.
string IntToString(int n){
if(n==0){
return "";
}else{
return IntToString(n/10) + (char)((n%10)+48);
}
}