I am asked to write a program using recursion. when input n, then program will generate all length n bits strings in increasing order.
e.g. n=2, output:00,01,10,11
n=3, output:000,001,010,011,100,101,110,111
here is my code:
#include <iostream>
#include <string>
using namespace std;
void bitString(int x,string prefix){
if (x == 0)
cout << prefix <<endl;
for (int i = 0;i<x;++i){
bitString(x-1,(prefix+"0"));
bitString(x-1,(prefix+"1"));
} }
int main (){
int n;
cin >> n;
and if i would like to make the program display in such a way that any two gray code in consecutive differ by 1 bit? can i change this above program to generate such outputs?
well, i wonder y our teacher wants us to think of a way to generates these output. I understand the first one's logic, but i have no clue to write the second one :'(
#include <iostream>
#include <string>
#include<cmath>
usingnamespace std;
void print(int num_of_digit, unsigned num)
{
cout<<num<<endl; //this is for test.
// Remove the above line and
//write a code to print num into binary with num_of_digit
}
unsignedshort binaryToGray(unsignedshort num)
{
return (num>>1) ^ num;
}
int main ()
{
int n;
unsigned num;
cin >> n;
//bitString(n,"");
for(unsigned i=0;i< pow(2,n);i++)
{
num = binaryToGray(i);
print(n,num);
}
//system ("pause");
return 0;
}