I am trying to create the binary representation of a given integer, however, when I try to output the string, binaryNum, at the end of the code, nothing is printed. However, if I run cout within the for loop, it will print out the binary representation as the program adds 0's and 1's (I only want the final output, not the steps along the way).
What am I missing?
#include <string>
#include <iostream>
using namespace std;
int main() {
int num;
string binaryNum = "";
int divisor = 1;
cin >> num;
while (num > 0) {
while (num / divisor > 1) {
divisor *= 2;
}
if (num / divisor == 1) {
binaryNum.push_back('1');
num = num - divisor;
divisor /= 2;
while (num / divisor < 1) {
divisor /= 2;
binaryNum.push_back('0');
}
}
}
cout << binaryNum << endl;
return 0;
}
Thanks!