Write a C++ function for converting decimal number into binary form using stack. code example

Example 1: convert int to binary string c++

std::string str = std::bitset<8>(123).to_string();

Example 2: Print Decimal to binary using stack

#include<iostream>
#include<stack>
using namespace std;
void dec_to_bin(int number) {
   stack<int> stk;
   while(number > 0) {
      int rem = number % 2; //take remainder
      number = number / 2;
      stk.push(rem);
   }
   while(!stk.empty()) {
      int item;
      item = stk.top();
      stk.pop();
      cout << item;
   }
}
main() {
   int num;
   cout << "Enter a number: ";
   cin >> num;
   dec_to_bin(num);
}

Tags:

Cpp Example