This is the syntax highlighted version of Binary2.java.
/*************************************************************************
* 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);
}
}
Last updated: Wed Feb 11 18:07:23 EST 2004
.
Copyright © 2004, Robert Sedgewick and Kevin Wayne.