PayPal Interview Question

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

Interview Answers

Anonymous

Jan 21, 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

Anonymous

Oct 25, 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); }

Anonymous

Jul 6, 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; }

Anonymous

Dec 30, 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); } }

Anonymous

Jan 21, 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) ); }