1

I have a method that prints out binary formar of numbers:

private static void binary(int n){
   for(int i = 1; i < Math.pow(2, n); i++)
      System.out.println(Integer.toBinaryString(i));
   }
} 

Output is like for n = 3:

1
10
11
100
101
110
111

Is there a way to print out like this:

001
010
011
100
101
110
111
hamid
  • 2,033
  • 4
  • 22
  • 42

5 Answers5

3
    private static void binary(int n){
       String t = ""; int N = 1<<n;
       for (int i=0; i<n;i++) t += "0";
       for (int i = 1; i < N; i++) {
             String s = Integer.toBinaryString(i);
             System.out.println(t.substring(s.length())+s);
       }
    } 
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • if n = 4, I have to change "000" to "0000"! – hamid Jan 10 '13 at 13:26
  • @Sam Fixed, sorry. I hadn't got the exact requirement. – Denys Séguret Jan 10 '13 at 13:27
  • 2
    A good interview question: What is the most inefficient part of this code and how could you change it? ;) – Peter Lawrey Jan 10 '13 at 13:35
  • is it `String s` inside the loop? just declare it outside the loop. – hamid Jan 10 '13 at 13:44
  • 1
    Moving the declaration doesn't change the performances. Peter might have been pointing to the repeated use of Math.pow (it's a slow function but maybe it's automatically optimized by compilers today for powers of 2). Using StringBuilders instead of concatenating strings might have an impact but probably barely measurable. What's really slow here is the println but you can't really avoid it, you just could do it less often. – Denys Séguret Jan 10 '13 at 13:51
2

I would write it as

private static void binary(int n){
   for(long i = 0, max = 1 << n; i < max; i++) {
      String s = Long.toBinaryString(i);
      while (s.length() < n) s = '0' + s;
      System.out.println(s);
   }
} 

or more efficiently

private static void binary(int n) {
    char[] chars = new char[n];
    for (long i = 0, max = 1 << n; i < max; i++) {
        for (int j = 0; j < n; j++)
            chars[j] = (char) (((i >>> (n - j - 1)) & 1) + '0');
        System.out.println(chars);
    }
}

binary(3);

prints

000
001
010
011
100
101
110
111
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

Quick/Dirty version:

System.out.println(Integer.toBinaryString(i+(1<<n)).substring(1));

(obvious flaw if n == the number of bits in an integer, or if you have more bits in your integer than you want to print... so limited, but maybe a bit simpler if you know your inputs)

JasonD
  • 16,464
  • 2
  • 29
  • 44
  • A slightly different scheme is to concat "0000" to the front of the string and then take a fixed-length tail. The only problem is that Java doesn't have a `tail()` method, so you have to do ugly computation to figure the starting point. – Hot Licks Jan 10 '13 at 13:31
  • Yes, but the other solutions here already did that, so I decided to show a (mostly) numerical alternative. – JasonD Jan 10 '13 at 13:33
  • (But I've used your solution in the past, too.) – Hot Licks Jan 10 '13 at 13:34
  • The other solutions sure went around Robin Hood's barn to do it. – Hot Licks Jan 10 '13 at 13:35
2

Try:

String.format("%" + n + "s", Integer.toBinaryString(i)).replace(' ', '0')

It may not be the most efficient solution, but it's simple and short enough.

Hui Zheng
  • 10,084
  • 2
  • 35
  • 40
0
private static void binary(int n){
   for(int i = 1; i < Math.pow(2, n); i++)
      System.out.println(String.format("%04d", Integer.parseInt(Integer.toBinaryString(i))));
   }
} 

How can I pad an integers with zeros on the left?

Community
  • 1
  • 1
ldam
  • 4,412
  • 6
  • 45
  • 76
  • That's wrong. the return value of `Integer.toBinaryString` is `String`, not integer. – Hui Zheng Jan 10 '13 at 13:56
  • Edited, I realised that as I posted. Come to think of it I don't really like how it has to be parsed again. – ldam Jan 10 '13 at 13:56