C++ program to Solve Tower of Hanoi Problem using Binary Value


This C++ program displays the solution to the Tower of Hanoi problem using binary value.

There is one binary digit for each disk.

The most significant bit represents the largest disk. A value of 0 indicates that the largest disk is on the initial peg, while a 1 indicates that it’s on the final peg.

The bitstring is read from left to right, and each bit can be used to determine the location of the corresponding disk.

The corresponding disk is stacked on top the previous disk on the same peg if a bit has the same value as the previous one.

If it is different that means that the corresponding disk is one position to the left or right of the previous one.

Algorithm

Begin
   Take the number of disk n as input.
   Declare n and a.
   Make a for loop a = 1 to (1<<n) – 1
   //
   Here, (a & a – 1) = bitwise AND with a and a – 1.
      (a | a – 1) = bitwise OR with a and a – 1.
         Here % means modulus operator.
   //
   Print the result indicating that moving disks from peg number (a & a – 1) % 3 to peg number ((a | a – 1) + 1) % 3
End

Example

#include<iostream>
using namespace std;
int main() {
   int n, a;
   cout<<"\nEnter the no of Disks: ";
   cin>>n;
   for (= 1; a < (1 << n); a++) {
      cout<<"\nDisk Move from Peg "<<(a&a-1)%3 <<" to Peg "<<((a|a-1)+1)%3;
   }
   cout<<"\n";
}

Output

Enter the no of Disks: 3
Disk Move from Peg 0 to Peg 2
Disk Move from Peg 0 to Peg 1
Disk Move from Peg 2 to Peg 1
Disk Move from Peg 0 to Peg 2
Disk Move from Peg 1 to Peg 0
Disk Move from Peg 1 to Peg 2
Disk Move from Peg 0 to Peg 2

Updated on: 30-Jul-2019

239 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements