Very Hard Recursion Problem?

Hey, I just had an exam on recursion and the question was much harder than I anticipated. It asked us to write a function called cutAfter7 that "cuts" a number at the first 7 in its digits. If the number is negative or does not contain a 7, the number is outputed as it is.

Here are a few examples of how the function is called and what the function would output:

1
2
3
4
5
6
  int main () {
  cout << cutAfter7 (147) << endl;        //prints 147
  cout << cutAfter7 (171717) << endl;    //prints 17  
  cout << cutAfter7 (666) << endl;      //prints 666
  cout << cutAfter7 (-3) << endl;      //prints -3
  }


What really confused me was how I could go about returning a number like 666 if each recursive call was testing the number (x/10) meaning I would not have access to the original (unchanged) number. Maybe I'm just over-analyzing and it's not hard at all? I'd love to hear your comments.
Last edited on
¿how would you return a number like 147 if you would not have access to the unchanged number?

you don't even explain your approach, start there.
> if each recursive call was testing the number (x/10)
> meaning I would not have access to the original (unchanged) number.

Unless you already had x, you wouldn't be able to pass x/10 to the recursive call.

1
2
3
4
5
6
7
8
9
bool ends_in_seven( int n ) { return n%10 == 7 || n%10 == -7 ; }

int cut_after_seven( int n )
{
    if( n < 10 && n > -10 ) return n ;

    const int residue = cut_after_seven(n/10) ;
    return ends_in_seven(residue) ? residue : n ;
}

http://coliru.stacked-crooked.com/a/af8948a1a80e7746
Topic archived. No new replies allowed.