-1

I'm trying to make a binary-to-decimal converter on my own. I tried arrays, but with unspecified lengths of binary representations for each number, I found it hard to use them. So now I'm trying with a ternary operator, and it works but the result is showing left-to-right when the correct answer should be right-to-left. Do anyone have a better method or way to make this thing right?

#include <iostream>

using namespace std;

//function that converts decimal to binary
string DecimaltoBinary(int d){

//variable that is going to store the binary representation
string decimal;

    //keep dividing by 2 till variable d reaches 0
    while(d!=0){

        //variabable decimal is going to store the binary representation
        decimal += (d % 2 == 0 ? "0": "1");

        //decimal number divided by 2
        d /= 2;
    }
    //this function is going to return the binary representation
    return decimal;
}

int main(){
    
    int decimal;

    cout<<"Input the decimal number: "<<endl;

    cin>>decimal;

    cout<<DecimaltoBinary(decimal)<<endl;
    
    return 0;
}

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

1 Answers1

1

The simplest solution using your existing code is just to reverse the assignment:

decimal = (d % 2 == 0 ? "0": "1") + decimal;
Ken White
  • 123,280
  • 14
  • 225
  • 444