INTRODUCTION TO COMPUTER SCIENCE
Robert Sedgewick and Kevin Wayne


This is the syntax highlighted version of Binary.java.


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

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

        // find smallest power of two greater than or equal to N
        int v = 1;
        while (v <= N/2)
            v = v * 2;
  
        // cast out powers of 2 
        while (v > 0) {
           if (N < v) { System.out.print(0);             }
           else       { System.out.print(1);  N = N - v; }
           v = v / 2;
        }

        System.out.println();


   }

}


Last updated: Wed Feb 11 18:07:23 EST 2004 .
Copyright © 2004, Robert Sedgewick and Kevin Wayne.