public class Hanoi { public static void main(String[] args) { String ans = ""; ans = hanoi(4, 1, 3, 2); System.out.println(ans); } public static String hanoi(int n, int fr, int to, int h) { if ( n == 1 ) { // base case return fr + " --> " + to + "\n"; } else { String helpSol1 = hanoi(n-1, fr, h, to); String helpSol2 = hanoi(n-1, h, to, fr); String myMove = fr + " --> " + to + "\n"; String mySol = helpSol1 + myMove + helpSol2; return mySol; } } }