Hello I am studying recursion and having trouble reading the following code below
public class MysteryClass {
/**
* Mystery method that performs a function recursively.
*
* @param x an integer > 0
* @param y an integer > 0 and < x
* prints result
*/
public static void mysteryMethod(int x, int y) {
if (x == 0) {
return;
} else {
mysteryMethod(x / y, y);
System.out.print(x % y);
}
}
public static void main(String[] args) {
mysteryMethod(13,2);
}
}
I had two possible solutions(and realized both are wrong)
Solution 1
therefore 1011
Solution 2
therefore return nothing
but the correct answer was 1101
Can anyone have a look at the code and explain me why 1101 is the correct answer and why my solutions are wrong?
That is because you did the recursion then print the number, you should print the number then recursion, that is:
public static void mysteryMethod(int x, int y) {
if (x == 0) {
return;
} else {
System.out.print(x % y);//exchange the position of the two lines of code
mysteryMethod(x / y, y);
}
}
In you code, you're printing the number backward...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.