Pergunta de entrevista da empresa PayPal

Consider the following function: int f (int num) { int out = 0; for (; num > 0; num /= 10) { int d = num % 10; out *= 10; out += d; } return out; } 1) What does it do? 2) Write the same algorithm using recursion

Respostas da entrevista

Sigiloso

21 de jan. de 2012

Sorry my answer previously posted was wrong. Here is the correct one without golbal or static variables, which is basically the same as the first one by Paul. inf f(int num, int car=0) { car *=10; if((num/10) == 0) return ( car + num ); else return f(num/10, car+(num%10) ); }

2

Sigiloso

25 de out. de 2012

private static int reverse(int n, int r) { if (n == 0) return r; return reverse(n/10, 10*r+n%10); } public static int reverse(int n) { return reverse(n, 0); }

Sigiloso

6 de jul. de 2015

Simple method without using global variable. static int reverseRecursive(int number, int sum) { if (number != 0) { int temp = number % 10; sum = sum * 10 + temp; return reverseRecursive((number / 10), sum); } else return sum; }

Sigiloso

30 de dez. de 2011

There is a trick that need global variable or static variable to record the temper sum. so the function declaration cannot be same as loop version if don't use global or static variable. the output parameter b will be the reverse result. void rev(int d, int& b) { b *= 10; if (d/10 == 0) b += d; else { b += d%10; rev(d/10, b); } }

Sigiloso

21 de jan. de 2012

You can do it without the golbal or static variables: int f(int num) { if((num/10) == 0) return num; else return ( 10(num%10) + f(num/10) ); }