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.
Here is my code:
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);
}
}
Is there any way to make this shorter or more efficient?