My task is to print an n-bit(n is accepted as input from user) binary sequence as :
For n=4,
Output:
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111

I found three ways to do this:
Algo 1. Run a loop for i=0 to 2^(n), step i by 1
print(Dec2Bin(i,n));

where Dec2Bin is a function that converts a decimal i into a String of size n (if possible without data value damage/loss )

Code for this algorithm:

Algo 2. Create a bit array
Check bits from right (LSB) to left (MSB).
if bitvalue @ index == 0, flip bit @ index to 1
else if bitvalue @ index == 1, recursively check for left bits,
as terminal case.. if bit @ index=0 is 0 n all bits to the right are 1
flip bit at index=0 to 1 and flip all the bits to the right to 0

I tried implementing this algo, but it didnt work well,, it gives me the same output for n>4, as that given by n=4.
I would be glad if someone could help me with debugging/fixing this piece of code.
My Code :

Algo 3. I just thought that maybe every bit 0 or 1 can be calculated dynamically and directly displayed..
using the Bin2Dec single bit conversion in simpler steps as shown in this code snippet, but unfortunately even this doesnt work:

Any help is appreciated... I want to fix the code, atleast there is a silly logical error in Algo 3.
Algo 2 seems a little too weird.. But still i guess it does work if coded well.

I would have thought you can reduce those algorithms to about ten lines, including lines with only a { on. I would use a StringBuilder rather than toBinaryString. The + operator for String catenation is possible, but less efficient if used in several statements.

Campbell Ritchie wrote: The + operator for String catenation is possible, but less efficient if used in several statements.

True, but lets get real, for any actual use of this code, performance is not relevant.
Even if one approach is ten times slower, no one will ever notice.

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38509

23

posted

0

Miling Shah wrote: . . . where Dec2Bin is a function that converts a decimal i into a String of size n . . . .

Not in the example shown; it returns an int[].
A decimal to binary conversion is really simple. Look: