// Author : Apostolos Syropoulos // Program : Iterative solution of the towers of hanoi problem // using bitwise operators. // Date : November 26, 2000 // import java.io.*; public class hanoiG1 { static int moves=0; //number of moves so far static int getInt() { String line; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try { line = in.readLine(); int i = Integer.valueOf(line).intValue(); return i; } catch (Exception e) { System.err.println("***Error: Input is not a number.\n" + "Input assumed to be the number 1"); return 1; } } static void hanoi(int height) { for (int x=1; x < (1 << height); x++) moveDisk((char)((x&x-1)%3+65),(char)((((x|x-1)+1)%3)+65)); } static void moveDisk(char fromPole, char toPole) { moves++; System.out.print(fromPole); System.out.print(toPole); System.out.print(((moves % 20)==0) ? '\n' : ' '); } public static void main(String[] args) { long time1, time2; //for benchmarking int TowerHeight; System.out.println("Enter Tower height..."); System.out.print("?"); TowerHeight = getInt(); time1 = System.currentTimeMillis(); hanoi(TowerHeight); time2 = System.currentTimeMillis(); System.out.println(); System.out.print(time2-time1); //print execution time in msec System.out.println(" msec execution time"); } }