Binary2.java


Below is the syntax highlighted version of Binary2.java from §1.3 Conditionals and Loops.



/*************************************************************************
 *  Compilation:  javac Binary2.java
 *  Execution:    java Binary2 N
 *  
 *  Prints out N in binary.
 * 
 *  % java Binary2 5
 *  101
 *
 *  % java Binary2 106
 *  1101010
 *
 *  % java Binary2 0
 *  0
 * 
 *  % java Binary2 16
 *  10000
 *
 *  Limitations
 *  -----------
 *  Does not handle negative integers or 0.
 *
 *  Remarks
 *  -------
 *  could use Integer.toBinaryString(N) instead.
 *
 *************************************************************************/

public class Binary2 { 
    public static void main(String[] args) { 
        int N = Integer.parseInt(args[0]);
        String s = "";

        // repeatedly divide by two, and form the remainders backwards
        while (N > 0) {
            s = (N % 2) + s;
            N /= 2;
        }
        System.out.println(s);
   }
}


Copyright © 2007, Robert Sedgewick and Kevin Wayne.
Last updated: Tue Sep 29 16:17:41 EDT 2009.