IntegerToBinary.java


Below is the syntax highlighted version of IntegerToBinary.java from §2.3 Recursion.


/******************************************************************************
 *  Compilation:  javac IntegerToBinary.java
 *  Execution:    java IntegerToBinary n
 *
 *  Prints out the binary representation of the integer n.
 *
 *  % java IntegerToBinary 8
 *  1000
 *
 *  % java IntegerToBinary 366
 *  101101110
 *
 ******************************************************************************/

public class IntegerToBinary {

    public static void convert(int n) {
        if (n == 0) return;
        convert(n / 2);
        StdOut.print(n % 2);
    }

    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        convert(n);
        StdOut.println();
    }

}



Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:19:56 EDT 2022.