Senin, 16 Juli 2012

Algorithm Binary representation for Java Programming

Write a program IntegerToBinary.Java  that takes a positive integer N (in decimal) from the command line and prints out its binary representation. Recall, in program 1.3.7, we used the method of subtracting out powers of 2. Instead, use the following simpler method: repeatedly divide 2 into N and read the remainders backwards. First, write a while loop to carry out this computation and print the bits in the wrong order. Then, use recursion to print the bits in the correct order.


IntegerToBinary.java



/*************************************************************************
 *  Compilation:  javac IntegerToBinary.java
 *  Execution:    java IntegerToBinary N
 *  
 *  Prints out the binary representation of N.
 *
 *  % java IntegerToBinary 8
 *  1000
 *
 *  % java IntegerToBinary 366
 *  101101110
 *
 *************************************************************************/

public class IntegerToBinary {

   public static void convert(int n) {
      if (n == 0) return;
      convert(n / 2);
      System.out.print(n % 2);
   }

   public static void main(String[] args) {
      int N = Integer.parseInt(args[0]);
      convert(N);
      System.out.println();
   }

}



Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne.
Last updated: Fri Aug 5 12:25:48 EDT 2011.

Tidak ada komentar:

Posting Komentar