技術メモ

神奈川在住のITエンジニアの備忘録。おもにプログラミングやネットワーク技術について、学んだことを自分の中で整理するためにゆるゆると書いています。ちゃんと検証できていない部分もあるのでご参考程度となりますが、誰かのお役に立てれば幸いです。

指定した桁数の全ての2進数文字列を生成する。

競技プログラミングの問題を解いていて必要になったので、Javaで、指定した桁数の全ての2進数文字列のリストを生成するメソッドを作成した。

    List<String> generateZeroOneCombination (int length) {
        if (length < 1) {
            throw new IllegalArgumentException("Input length is less than 1.");
        }
        int max = (int) Math.pow(2, length);
        List<String> zeroOneCombination = new ArrayList<>();
        // String.format() に 2進数に変換するオプション(書式)がないので、以下のようにちょっと回りくどい方法を用いている。
        for (int i = 0; i < max; i++) {
            String binStr = Integer.toBinaryString(i);
            String formatter = "%" + length + "s";
            // String.format() で桁数を揃えてから、String.replace() で先頭部分の空白を 0 に置き換える。
            String binStrFormatted = String.format(formatter, binStr).replace(" ", "0");
            zeroOneCombination.add(binStrFormatted);
        }
        return zeroOneCombination;
    }


generateZeroOneCombinationに、例えば、引数に 3 を与えると、戻り値として以下の2進数文字列を含んだ List を返す。
"000", "001", "010", "011", "100", "101", "110", "111"