
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 (a = 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
- Related Articles
- Tower Of Hanoi Problem\n
- C Program for Tower of Hanoi
- Python Program for Tower of Hanoi
- C++ Program to Solve Knapsack Problem Using Dynamic Programming
- Python Program to solve Maximum Subarray Problem using Kadane’s Algorithm
- Python Program to solve Maximum Subarray Problem using Divide and Conquer
- C++ Program to Solve N-Queen Problem
- C++ Program to Solve the Dominating Set Problem
- Write a C# program to solve FizzBuzz problem
- C++ Program to Solve the Fractional Knapsack Problem
- C++ Program to Solve the 0-1 Knapsack Problem
- C++ Program to Solve Travelling Salesman Problem for Unweighted Graph
- How to solve diamond problem using default methods in Java
- How to solve the diamond problem using default methods in Java?
- C++ Program to Solve a Matching Problem for a Given Specific Case

Advertisements