print binary numbers in ascending order

巧了我就是萌 提交于 2020-01-06 14:57:11

问题


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.


回答1:


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;
    }
}


来源:https://stackoverflow.com/questions/17912363/print-binary-numbers-in-ascending-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!