Comp211_tutorial5 - MCST-CS

Kingdom of Saudi Arabia
Ministry of Higher Education
Al-Maarefa College for Science and Technology
Faculty of Computer Science and Information
Systems
COMP211 Tutorial 5
Write a Java program to convert a nonnegative integer in decimal format—that is, base
10—into the equivalent binary number—that is, base 2. First, we define some terms.
Let x be a nonnegative integer. We call the remainder of x after division by 2 the rightmost bit of x.
Thus, the rightmost bit of 33 is 1 because 33 % 2 is 1, and the rightmost bit of 28 is 0 because 28 %
2 is 0.
We first use an example to illustrate the algorithm to convert an integer in base 10 to the
equivalent number in binary format.
Suppose we want to find the binary representation of 35. First, we divide 35 by 2. The quotient is
17 and the remainder—that is, the rightmost bit of 35—is 1. Next, we divide 17 by 2. The quotient
is 8 and the remainder—that is, the rightmost bit of 17—is 1. Next, we divide 8 by 2. The quotient
is 4 and the remainder—that is, the rightmost bit of 8—is 0. We continue this process until the
quotient becomes 0.
The rightmost bit of 35 cannot be printed until we have printed the rightmost bit of 17. The
rightmost bit of 17 cannot be printed until we have printed the rightmost bit of 8, and so on. Thus,
the binary representation of 35 is the binary representation of 17 (that is, the quotient of 35 after
division by 2), followed by the rightmost bit of 35.
Thus, to convert a nonnegative integer num in base 10 into the equivalent binary number, we first
convert the quotient num / 2 into an equivalent binary number, and then append the rightmost bit
of num to the binary representation of num / 2.