简体   繁体   English

按升序打印二进制数字

[英]print binary numbers in ascending order

I was trying to print binary numbers in ascending order of 0's (00 then 01, 10, 11). 我试图以0的升序打印二进制数字(00依次为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. 但此操作不适用于0的升序。

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. 任何使用格雷码对此o / p进行优化的方法。

As your intention is just print out binary number representation of numbers from 由于您的意图只是打印出以下数字的二进制数字表示形式

zero to 2^k-1

Here's the Biset approach 这是Biset方法

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++ 此问题先前已用C ++标记

In C++, this will be even more straight forward: 在C ++中,这将更加直接:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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