简体   繁体   中英

How do I count in binary after specifying a given number of digits?

As one of the intermediate competition problems, we were tasked to list down all binary sequences with "n" digits until the maximum value. For example, if the input was

3

(3 digits) then the output would be

000
001
010
011
100
101
110
111

The problem I'm facing is that I don't know how to approach this problem. Previously, I could make a method using recursion to check for every previous digit, but I couldn't make the method expandable.

import java.util.Scanner;
import java.util.stream.IntStream;

public class MainClas {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        IntStream.range(0, (int) Math.pow(2, n))
                .forEach(i -> {
                    String s = String.format("%" + n + "s", Integer.toBinaryString(i)).replace(' ', '0');
                    System.out.println(s);
                });
    }
}

input:

3

output:

000
001
010
011
100
101
110
111

I've created a simple Solution which will print your expected output.

public class PrintBinaryTest {

    public static void main(String[] args) {
        printBinaryNumbers(3);
    }

    public static void printBinaryNumbers(int digits) {
        int maxNr = (int) (Math.pow(2, digits) - 1);
        for (int i = 0; i <= maxNr; i++) {
            System.out.println(getBinaryRepresentationWithLeadingZeros(i, digits));
        }
    }

    public static String getBinaryRepresentationWithLeadingZeros(int nr, int digits) {
        String binaryString = Integer.toBinaryString(nr); // without leading zeros
        String formatString = "%" + digits + "s";
        return String.format(formatString, binaryString).replace(' ', '0');
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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