Tower of Hanoi | Set 2 | Java program for the above approach ; Function to print order of movement of N disks across three rods to place all disks on the third rod from the first - rod using binary representation ; Iterate over the range [ 0 , 2 ^ N - 1 ] ; Print the movement of the current rod ; Driver Code
class GFG { static void TowerOfHanoi ( int N ) { for ( int x = 1 ; x <= Math . pow ( 2 , N ) - 1 ; x ++ ) { System . out . print ( " Move ▁ from ▁ Rod ▁ " + ( ( x & x - 1 ) % 3 + 1 ) + " ▁ to ▁ Rod ▁ " + ( ( ( x x - 1 ) + 1 ) % 3 + 1 ) + "NEW_LINE"); } } public static void main ( String [ ] args ) { int N = 3 ; TowerOfHanoi ( N ) ; } }