4 4 4
ata Structures and Algo
4 4 4
rithms in Java, 6e Mich
4 4 4 4
ael Goodrich, Roberto
4 4 4
Tamassia (All Chapter 4 4
s)
, Chapter
1 Java Primer
4
Hints and Solutions
4 4
Reinforcement
R-
1.1)4 Hint4Use4 the4 code4 templates4 provided4 in4 the4 Simple4 Input4 and4O
utput4section.
R-1.2)4Hint4You4may4read4about4cloning4in4Section43.6.
R-
1.2)4Solution4Since,4after4the4clone,4A[4]4and4B[4]4are4both4pointing4to4t
he4same4GameEntry4object,4B[4].score4is4now4550.
R-1.3)4Hint4The4modulus4operator4could4be4useful4here.
R-1.3)4Solution
public4boolean4isMultiple(long4n,4long4m)4{
return4(n%m4==40);
}
R-1.4)4Hint4Use4bit4operations.
R-1.4)4Solution
public4boolean4isEven(int4i)4{
return4 (i4 &4 14 ==4 0);
}
R-
1.5)4Hint4The4easy4solution4uses4a4loop,4but4there4is4also4a4formula4for4t
his,4which4is4discussed4in4Chapter44.
R-1.5)4Solution
public4int4sumToN(int4n)4{
int4 total4=4 0;
for4(int4j=1;4j4<=4n;4j++)4tot
al4+=4j;
return4 total;
}
,2 Chapter41.4 Java4Primer
R-1.6)4Hint4The4easy4thing4to4do4is4to4write4a4loop.
R-1.6)4Solution
public4int4sumOdd(int4n)4{
int4 total4=4 0;
for4(int4j=1;4j4<=4n;4j4+=42)4
total4+=4j;
return4 total;
}
R-1.7)4Hint4The4easy4thing4to4do4is4to4write4a4loop.
R-1.7)4Solution
public4int4sumSquares(int4n)4{
int4 total4=4 0;
for4(int4j=1;4j4<=4n;4j++)4tot
al4+=4j∗j;
return4 total;
}
R-1.8)4Hint4You4might4use4a4switch4statement.
R-1.8)4Solution
public4int4numVowels(String4text)4{
int4 total4=4 0;
for4(int4j=0;4j4<4text.length();4j++)4{
switch4(text.charAt(j))4{
case4'a':
case4'A':
case4'e':
case4'E':
case4'i':
case4'I':
case4'o':
case4'O':
case4'u':
case4'U':4tot
al4+=41;
}
}
return4 total;
}
R-1.9)4Hint4Consider4each4character4one4at4a4time.
, 3
R-
1.10)4Hint4Consider4using4get4and4set4methods4for4accessing4and4mod-
4ifying4the4values.
R-
1.11)4 Hint4The4traditional4 way4 to4 do4 this4 is4 to4use4 setFoo4 methods,4w
here4Foo4is4the4value4to4be4modified.
R-1.11)4Solution
public4void4setLimit(int4lim)4{
limit4=4lim;
}
R-1.12)4Hint4Use4a4conditional4statement.
R-1.12)4Solution
public4void4makePayment(double4amount)4{
if4(amount4>40)4balanc
e4− =4amount;
}
R-1.13)4Hint4Try4to4make4wallet[1]4go4over4its4limit.
R-1.13)4Solution
for4(int4val=1;4val4<=458;4val++)4{4wallet[0
].charge(3∗val);4wallet[1].charge(2∗val);4
wallet[2].charge(val);
}
This4change4will4cause4wallet[1]4to4attempt4to4go4over4its4limit.
Creativity
C-1.14)4Hint4The4Java4method4does4not4need4to4be4passed4the4value4of4n
as4an4argument.
C-1.15)4Hint4Note4that4the4Java4program4has4a4lot4more4syntax4require-
4ments.
C-
1.16)4Hint4Create4an4enum4type4of4all4operators,4including4=,4and4use4a
n4array4of4these4types4in4a4switch4statement4nested4inside4for-
loops4to4try4all4possibilities.
C-
1.17)4Hint4Note4that4at4least4one4of4the4numbers4in4the4pair4must4be4eve
n.
C-1.17)4Solution