1
I have a recursion challenge. The goal is to return "n + the sum of the last digit on the left". Example:
Input: 54321
Output: 54326 (54321 + 5)
But the only way I could was like this:
#include <stdio.h>
int somault(int n){
if(n < 10) return n;
return somault(n/10);
}
int main() {
int n;
scanf("%d", &n);
printf("%d", n+somault(n));//A soma é realizada aqui, não dentro da função.
return 0;
}
It is possible to return this value meeting the following criteria?
- Only one function
- Recursive function
- Not using vectors, global variables and/or pointers
I tried other ways, but none returned the correct value. Precisely because I can’t get the value of the last call and only do with the first one. I tried to use static
to count or divide increasing the base 10 to catch the last, but did not work.
But is it possible to use external variables ? Depending on the entire list of requirements can drastically change the solution and so I advise you to specify them all clearly. With a global variable outside can also get there, but something tells me that also can not do this lol
– Isac
The problem is actually another, but I don’t know if it can change anything. So... Put the whole problem? With the solution you had made? Maybe the one I made based on the other can have solution. But the rules are the same.
– Leonardo Rodrigues Dos Santos
The problem is another ? But what then ? The restrictions apparently were not all discriminated against. You can always change the question by editing it and making it clearer, as suggested. But if there’s another solution that I had developed with another code, maybe it’s something for another question, hard to say.
– Isac
The solution is to return if n-4 if the leftmost digit is even, or n-3 if it is odd.
– Leonardo Rodrigues Dos Santos
If you have a solution that solves the problem in the way you expected, then the ideal is to put it as an answer.
– Isac