// CSE 143, Winter 2009, Marty Stepp // 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(); System.out.println(pow(3, 4)); } // 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 < 2) { // recursive case: n == 0 or n == 1 // it has the same binary representation, so just print it System.out.print(n); } else { // recursive case: n >= 2 // chop off last digit; use recursion for the rest printBinary(n / 2); printBinary(n % 2); } } // Returns (base) raised to the (exponent) power, recursively. // Precondition base >= 0 and exponent >= 0 public static int pow(int base, int exponent) { if (exponent == 0) { // base case: x^0 == 1 for all x return 1; } else if (exponent % 2 == 0) { // optimization: x^y == (x^2)^(y/2) if y is even int half = pow(base, exponent / 2); return half * half; } else { // x^y == x * x^(y-1) return base * pow(base, exponent - 1); } } }