Reputation: 1
I codded a program to print n-bit binary gray codes. But I'm not sure if it is a backtracking program. If it is not a backtracking program, what is something I can do to use it in this code.
I want to print the binary codes themselves, not their decimal equivalent.
vector<string> grayCode(int n)
{
if(n<=0)
return {"0"};
if(n == 1)
return {"0", "1"};
vector<string> list1 = grayCode(n-1);
vector<string> mainList;
for(int i=0; i<list1.size(); i++)
mainList.push_back("0" + list1[i]);
for(int i=list1.size()-1; i>-1; i--){
mainList.push_back("1" + list1[i]);
return mainList;
}
int main()
{
vector<string> gcode = grayCode(4);
for(int i=0; i<gcode.size(); i++)
cout<< gcode[i] << " ";
return 0;
}
Upvotes: 0
Views: 177
Reputation: 12332
I want to print the binary codes themselves, not their decimal equivalent.
That should be your question. None of it has to do with grey code or backtracking. It's a simple output formatting question.
You can change the output format using for example std::hex
like this:
std::cout << std::hex << gcode[i] << " ";
That will output the value in hexadecimal. There is also std::oct
for octal. Sadly there is no std::bin
for binary. And std::cout.setbase(2);
will also not work.
I think the simplest is to use std::bitset
, specifically the to_string()
.
Upvotes: 0