// CSE 143, Autumn 2013 // This program demonstrates a recursive printBinary method that // prints the binary representation of an integer. // // We also wrote a recursive pow method today which is included below. public class Binary { public static void main(String[] args) { printBinary(-4); // 100 System.out.println(); printBinary(12); // 1100 System.out.println(); printBinary(21); // 10101 System.out.println(); printBinary(42); // 101010 System.out.println(); printBinary(69743); // 10001000001101111 System.out.println(); } // Prints the binary representation of the given integer. // For example, printBinary(42) prints 101010. // Precondition: n >= 0 public static void printBinary(int n) { if(n < 0) { System.out.print("-"); printBinary(-n); } else if ( n < 2) { System.out.print(n); } else { int last = n % 2; int rest = n / 2; // print the rest of the number printBinary(rest); System.out.print(last); } } }