Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

java - Print list of binary permutations

What I am trying to do is print all the possibilities of a binary number n digits long. In other words, with a 4 digit number:

0001
0010
0100
1000

..etc

To be honest, I have no idea of where to even start with this (other than I figure I'd need to use a loop, and probably an array) so any pointers in the right direction would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Maybe you could use a recursive algorithm:

public void printBin(String soFar, int iterations) {
    if(iterations == 0) {
        System.out.println(soFar);
    }
    else {
        printBin(soFar + "0", iterations - 1);
        printBin(soFar + "1", iterations - 1);
    }
}

You would execute this like this:

printBin("", 4);

That would give you all possible binary numbers with 4 digits.

Hope this helped!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...