THINK FIRST·CODE LATER

← All labs

Decimal to binary with a loop

Problem

ToBinary reads whole numbers until a negative number ends the input. For each number it prints its binary form, the number of bits and how many of them are 1.

Build the binary form yourself, without Integer.toBinaryString: the remainder of the division by 2 is the last bit; divide by 2 and repeat until nothing is left. For the input

13 255 0 1024 7 -1

the program prints

13 = 1101 (4 bits, 3 ones)
255 = 11111111 (8 bits, 8 ones)
0 = 0 (1 bits, 0 ones)
1024 = 10000000000 (11 bits, 1 ones)
7 = 111 (3 bits, 3 ones)

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

l7-8-data-1.txt

13 255 0 1024 7 -1
What your program must print for l7-8-data-1.txt
13 = 1101 (4 bits, 3 ones)
255 = 11111111 (8 bits, 8 ones)
0 = 0 (1 bits, 0 ones)
1024 = 10000000000 (11 bits, 1 ones)
7 = 111 (3 bits, 3 ones)

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < l7-8-data-1.txt

Windows PowerShell does not understand <:

Get-Content l7-8-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.