Sum of n + last digit from left

1

I'm having a recursion challenge. The goal is to return "n + the sum of the last digit to the left". Example:

Entry: 54321

Output: 54326 (54321 + 5)

But the only way I got it 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;
}

Is it possible to return this value based on the following criteria?

  • Only one function
  • Recursive function
  • Without using vectors, global variables and / or pointers

I tried other ways, but none returned the correct value. Just because I can not get the value of the last call and only do with the first call. I tried to use static to count or split by increasing base 10 to get the last but did not work.

    
asked by anonymous 05.11.2018 / 00:50

2 answers

3

I personally think that these types of challenges that force a specific recursive solution are not very good, and end up generating code rather non-intuitive and unusual, and that in the end has no applicability in the real world.

Still if nothing is indicated in relation to the number of parameters of the function then you can pass to receive two parameters, in which the same number in both passes. In one of them it goes walking until arriving at the first digit and in the other it maintains the original number for the sum:

#include <stdio.h>

int somault(int n, int original){
   if(n < 10) return n + original;
   return somault(n/10, original);
}

int main() {
   int n;
   scanf("%d", &n);
   printf("%d", somault(n, n));
   return 0;
}

See it working on Ideone

By reinforcing, this would be of no use in real code, but it complies with the requirements it has set, and generates the expected response.

    
05.11.2018 / 01:18
0

Solution:

#include <stdio.h>

int somault(int n){
   if(n/10 < 10) return n-n/10;
   return n+(n/10-somault(n/10));
}

int main() {
   int n;
   scanf("%d", &n);
   printf("%d", somault(n));
   return 0;
}

I'll explain the operation later.

    
05.11.2018 / 03:31