HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Print all binary strings of length n

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
alllengthprintbinarystrings

Problem

I have completed my homework with directions as follows:


Declare and implement a class named Binary. This class will have a
method named printB(int n) that prints all binary strings of length n.
For n = 3, it will print

000
001
010
011
100
101
110
111




in this order.

Is there any way to make this shorter or more efficient?

import java.util.Scanner;
class Binary
{

    String B;
    int temp;

    void printB(int n)
    {
        for(int i = 0; i < Math.pow(2,n); i++)
        {
            B = "";
            int temp = i;
            for (int j = 0; j < n; j++)
            {
                if (temp%2 == 1)
                    B = '1'+B;
                else
                    B = '0'+B;
                    temp = temp/2;
            }
            System.out.println(B);
         }
    } 
}

class Runner
{
    public static void main(String [] args)
    {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter n:");
        int n = in.nextInt();

        Binary myB = new Binary();

        myB.printB(n);
    }
}

Solution

Is there any way to make this shorter or more efficient?

Yes, we can do some things.

for(int i = 0; i < Math.pow(2,n); i++)


You calculate the pow for every iteration. The pow call takes some time (compared to basic things like multiplication or addition), you should do it only once.

B = "";
B = '1'+B;
B = '0'+B;


You will create a lot of string copies for every string concatenation. This costs a lot of perfomance. In general, you should use a StringBuilder.

In this special case, we could even use a char array.

for(int i = 0; i < Math.pow(2,n); i++)
if (temp%2 == 1)
temp = temp/2;


You could use bit manipulations. But depending on the jvm or hotspot compiler, this will be done anyway.

void printB(int n)
        B = "";
        int temp = i;


Overall point: avoid abbreviations.

All together, it could be like this:

void printAllBinaryUpToLength(final int length) {
    if (length >= 63)
        throw new IllegalArgumentException("Current implementation supports only a length  0) {
            buffer[--bufferPosition] = (char) (48 + (currentNumber & 1));
            currentNumber >>>= 1;
        }
        System.out.println(buffer);
    }
}


Calculates (without printing, printing takes the great majority of every loop) results up to 25 (2^25 = ~33*10^6) in less than a second. Should be enough.

Code Snippets

for(int i = 0; i < Math.pow(2,n); i++)
B = "";
B = '1'+B;
B = '0'+B;
for(int i = 0; i < Math.pow(2,n); i++)
if (temp%2 == 1)
temp = temp/2;
void printB(int n)
        B = "";
        int temp = i;
void printAllBinaryUpToLength(final int length) {
    if (length >= 63)
        throw new IllegalArgumentException("Current implementation supports only a length < 63. Given: " + length);
    final long max = 1 << length;
    for (long i = 0; i < max; i++) {
        long currentNumber = i;
        final char[] buffer = new char[length];
        int bufferPosition = buffer.length;
        while (bufferPosition > 0) {
            buffer[--bufferPosition] = (char) (48 + (currentNumber & 1));
            currentNumber >>>= 1;
        }
        System.out.println(buffer);
    }
}

Context

StackExchange Code Review Q#24690, answer score: 3

Revisions (0)

No revisions yet.