【问题标题】:print binary numbers in ascending order按升序打印二进制数
【发布时间】:2013-07-28 20:08:07
【问题描述】:

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

使得零在前面。

我尝试使用来自 here 的以下代码,但这并没有给出正确的操作 (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 的升序。

所以我不得不处理这段代码中的字符串 (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 的任何方法。

【问题讨论】:

  • 您希望优化什么?
  • 第一个使用格雷码使得o/p为(00,01,10,11)...希望这很清楚
  • 你不只是打印来自0 to 2^k-1 的二进制表示吗?
  • 订单 (00,01,10,11) 不是格雷码。对于格雷码,连续的元素必须只改变一位;您的第二个和第三个元素(01 和 10)有两位不同。正确的格雷码是 (00,01,11,10) 或 (00,10,11,01)。那么你想要格雷码顺序还是数字顺序? (或者别的什么?)
  • @P0W 是的...(stackoverflow 的填充)

标签: java recursion tail-recursion


【解决方案1】:

因为您的意图只是从

中打印出数字的二进制数表示

zero to 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++ 标记过

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

【讨论】:

  • 感谢@POW 的努力
猜你喜欢
  • 2023-01-30
  • 2023-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-21
  • 2012-02-23
  • 1970-01-01
相关资源
最近更新 更多