Display both the original integer and the binary output

Anonymous
timer Asked: Sep 13th, 2013
account_balance_wallet $5

Question Description

- Prompt the user for a positive integer less than 100.
- Convert the integer into its binary representation, you MUST hard code the solution with your own algorithm with loop NOT using the java buit-in method such as: Integer.toBinaryString(int ).
- Display both the original integer and the binary output.

Tutor Answer

jdwilliams51
School: University of Virginia

Here's the Java program that works.  For a dollar you don't get much error checking or formatting.  Please contact me if you need any additional help.  Depending on what you want it could be free or cost a little $$.


import java.util.Scanner;

public class Integer2Binary {

  private static Scanner kb = new Scanner(System.in);

  public static void main(String[] args) {
  System.out.println(
  "\nProgram to get postive integer < 100 and convert to binary\n");
  int n;
  do {
  System.out.print("Enter an integer (0<n<100): ");
  n = kb.nextInt();
  } while (!(0 < n && n < 100));
  int nSav = n;
  // convert the int to binary:
  String binStr = "";
   
// since n<100, the largest power of 2 that fits will be 64 = 2^6
  binStr += n / 64;
  n = n % 64;
  binStr += n / 32;
  n = n % 32;
  binStr += n / 16;
  n = n % 16;
  binStr += n / 8;
  n = n % 8;
  binStr += n / 4;
  n = n % 4;
  binStr += n / 2;
  n = n % 2;
  binStr += n;
  // convert string to numbers:
  int binNum = Integer.parseInt(binStr);
  System.out.println(""
  + "\nThe original decimal integer: " + nSav
  + "\nThis number's binary equivalent is: " + binNum);
  }
}
Integer2Binary.java




flag Report DMCA
Review

Anonymous
Top quality work from this guy! I'll be back!

Brown University





1271 Tutors

California Institute of Technology




2131 Tutors

Carnegie Mellon University




982 Tutors

Columbia University





1256 Tutors

Dartmouth University





2113 Tutors

Emory University





2279 Tutors

Harvard University





599 Tutors

Massachusetts Institute of Technology



2319 Tutors

New York University





1645 Tutors

Notre Dam University





1911 Tutors

Oklahoma University





2122 Tutors

Pennsylvania State University





932 Tutors

Princeton University





1211 Tutors

Stanford University





983 Tutors

University of California





1282 Tutors

Oxford University





123 Tutors

Yale University





2325 Tutors