按升序打印二进制数 [英] print binary numbers in ascending order

查看:38
本文介绍了按升序打印二进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图以 0 的升序(00 然后是 01、10、11)打印二进制数.

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

这样之前的零.

我尝试使用 此处 但这并没有给出正确的操作(运行示例)

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

但此操作不适用于 0 的升序.

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

}

}

任何使用格雷码优化此 o/p 的方法.

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

零到 2^k-1

这里是 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");
    }
  }
}

这个问题之前被标记为 C++

This Question was earlier tagged with C++

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

这篇关于按升序打印二进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆