[Solved] Decimal to binary without arrays and binary-operators (like “&”)


Your current code checks for presence of the binary value from LSB to MSB, and prints in that order. One way to approach the issue would be to instead check from MSB to LSB.

#include <iostream>
int main(){
  int n, a=1;
  std::cin >> n;

  while(2*a <= n)
    a *= 2;                                                                                                               
  while(a > 0){
    if (n >= a){
      std::cout << 1;
      n -= a;
    } else {
      std::cout << 0;
    }
    a /= 2;
  }
  std::cout << std::endl;
  return 0;
}

This isn’t a great way to do this, and I recommend improving it or finding alternatives as an exercise.

solved Decimal to binary without arrays and binary-operators (like “&”)