Java Reference
In-Depth Information
line#
day
answer
output
35
0
44
1
47
1
53
1
56
3
62
0
71
0
80
1
83
19
85
Your birthday is 19!
This game is easy to program. You may wonder how the game was created. The mathematics
behind the game is actually quite simple. The numbers are not grouped together by accident—
the way they are placed in the five sets is deliberate. The starting numbers in the five sets are
1 , 2 , 4 , 8 , and 16 , which correspond to 1 , 10 , 100 , 1000 , and 10000 in binary (binary num-
bers are introduced in Appendix F, Number Systems). A binary number for decimal integers
between 1 and 31 has at most five digits, as shown in Figure 4.3a. Let it be b 5 b 4 b 3 b 2 b 1 . Thus,
b 5 b 4 b 3 b 2 b 1 =
mathematics behind the game
b 1 ,as shown in Figure 4.3b. If a day's binary
number has a digit 1 in b k , the number should appear in Set k . For example, number 19 is
binary 10011 , so it appears in Set1, Set2, and Set5. It is binary 1 + 10 + 10000 = 10011
or decimal 1 + 2 + 16 = 19 . Number 31 is binary 11111 , so it appears in Set1, Set2, Set3,
Set4, and Set5. It is binary 1 + 10 + 100 + 1000 + 10000 = 11111 or decimal 1 + 2 +
4 + 8 + 16 = 31 .
b 5 0000
+
b 4 000
+
b 3 00
+
b 2 0
+
Decimal
Binary
10000
1000
100
10
b 5
0
0
00
1
00001
b 4
00
0
2
00010
00011
10000
10
1
b 3
0
0
3
...
19
b 2
0
+
+
1
11111
b 1
b 5 b 4 b 3 b 2 b 1
+
10011
10011
19
...
31
11111
31
(a)
(b)
F IGURE 4.3
(a) A number between 1 and 31 can be represented using a five-digit binary
number. (b) A five-digit binary number can be obtained by adding binary numbers 1 , 10 ,
100 , 1000 , or 10000 .
4.21
If you run Listing 4.3 GuessBirthday.java with input 1 for Set1, Set3, and Set4 and 0
for Set2 and Set5, what will be the birthday?
Check
Point
4.5.2 Case Study: Converting a Hexadecimal Digit to a Decimal Value
The hexadecimal number system has 16 digits: 0-9, A-F. The letters A, B, C, D, E, and F
correspond to the decimal numbers 10, 11, 12, 13, 14, and 15. We now write a program that
prompts the user to enter a hex digit and display its corresponding decimal value, as shown
in Listing 4.4.
 
 
Search WWH ::




Custom Search