Just for a different look at the problem, since you already have a lot of answers.
It is true that a cover-based approach for solving recursion is to use a stack. However, if you know exactly what you decide, you can find an alternative solution. Or maybe not an alternative for sure - only one that will be more compact.
In this case, the function gives a binary representation of the parameter for integers greater than zero.
You may be tempted to use:
public static void foo(int number) { if ( number > 0 ) { System.out.print( Integer.toBinaryString(number) ); } }
But this, of course, can only earn points for courage in the test.
So here is an adaptation of how Java actually does this:
public static void foo(int number) { if (number > 0) { char[] chars = new char[32]; int charPos = 32; char[] digits = { '0', '1' }; do { chars[--charPos] = digits[number % 2]; number /= 2; } while (number > 0); System.out.print(new String(chars, charPos, 32 - charPos)); } }
This is actually using the stack, but not very complicated. A stack is just an array of characters that you start filling from the end, and go to the beginning. You can use such an array instead of a collection, because it is known that an int contains no more than 32 bits. This way you will never encounter the boundaries of an array. In truth, because you only work with positive numbers, it could even be a 31-character array.
So, in each case, you put the current digit in the current empty position in the array and move the pointer to the left. As a result, you convert all the characters that you have collected into a string using the String constructor, which, as convenient, can use the specified part of the character array.
The actual statements used by Java are slightly different:
do { chars[charPos--] = digits[number & 1]; number >>>= 1; } while (number != 0);
since shift and camouflage are more efficient operations than division. If you use this version, it is just as effective as when using Integer.toBinaryString() .