Java Reference
In-Depth Information
line#
output
day
answer
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 numbers 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 3.2a. Let it be Thus,
as shown in Figure 3.2b. If a day's binary
number has a digit
1
in 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
.
mathematics behind the game
b
5
b
4
b
3
b
2
b
1
.
b
5
b
4
b
3
b
2
b
1
=
b
5
0000
+
b
4
000
+
b
3
00
+
b
2
0
+
b
1
,
b
k
,
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
3.2
(a) A number between
1
and
31
can be represented using a 5-digit binary
number. (b) A 5-digit binary number can be obtained by adding binary numbers
1
,
10
,
100
,
1000
, or
10000
.
An
if-else
statement decides which statements to execute based on whether the
condition is true or false.
Key
Point
A one-way
if
statement takes an action if the specified condition is
true
. If the condition is
false
, nothing is done. But what if you want to take alternative actions when the condition is
false
? You can use a two-way
if-else
statement. The actions that a two-way
if-else
statement specifies differ based on whether the condition is
true
or
false
.