简体   繁体   中英

print binary numbers in ascending order

I was trying to print binary numbers in ascending order of 0's (00 then 01, 10, 11).

Such that the zeros are before.

I tried using the below code from here but this does not give the right op ( running sample )

void test2() {

    final int grayCodeLength = 4;

    // generate matrix
    final int grayCodeCount = 1 << grayCodeLength; // = 2 ^ grayCodeLength
    int grayCodeMatrix[][] = new int[grayCodeCount][grayCodeLength];
    for (int i = 0; i < grayCodeCount; i++) {
        int grayCode = (i >> 1) ^ i;
        for (int j =0;  j <grayCodeLength; j++) {
            // extract bit
            final int grayCodeBitMask = 1 << j;
            grayCodeMatrix[i][j] =  (grayCode & grayCodeBitMask) >> j;
        }
    }

    // view result
    for (int y = 0; y < grayCodeMatrix.length; y++) {
        for (int x = 0; x < grayCodeMatrix[0].length; x++) {
            System.out.print(grayCodeMatrix[y][x]);
        }
        System.out.print("\n");
    }
}

but this op is not for ascending order of 0's.

So i had to do with strings in this code ( running sample )

class Main
  {
    static int k = 4;
    public static void main (String[] args) throws java.lang.Exception
    {

            new Main().test7(k, "");
    }

    void test7(int i, String a) {

    a = a + "0";

    if (a.length() == k) {
        System.out.println(""+a);
        a = a.substring(0, a.length()-1);
        a =a +"1";
        System.out.println(a);
    }else {
        test7(i-1, a);
        if (a.length() >1) {
            a =a.substring(0, a.length()-1);
            a =a+"1";
        } else {
            a = "1";
        }
        test7(i-1,a);
    }

}

}

any way out to optimize for this o/p using gray code.

As your intention is just print out binary number representation of numbers from

zero to 2^k-1

Here's the Biset approach

public class BitTest {

  public static void main(String args[]) {

    int k = 4;
    BitSet bits;

    for(int x = 0;x< (1<<k) ;x++){
        bits= new BitSet(k);
    int i =  0;
    int v=x;
    while (v > 0) {
      if ( (v % 2) == 1 ) 
    bits.set(i);
      v = v/2;
      i++;
    }
    // print BitSet contents 
    for(i=k-1; i>=0; i--)
      System.out.print(bits.get(i)? 1 : 0);

    System.out.print("\n");
    }
  }
}

This Question was earlier tagged with C++

In C++, this will be even more straight forward:

#include <iostream>
#include <bitset>
#include <climits>
using namespace std;
int main()
{
    const int k=4;
    for(int i=0;i<1<<k;i++){
       bitset<k>    bits(i);
       cout << bits << endl;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM