Exercises

  1. Write the if statements that call different methods do0_9(), do10_99(), and do100_999() based on the value of i being in the range 0-9, 10-99, or 100-999. Don't forget to allow for other values of i, including negative values.

  2. Write a switch statement that corresponds to the if statement in question 1. Which is more compact? Which is easier to read?

  3. Write a method that counts the number of “1” bits in an int value. You can get successive bits from the end of an int by checking to see if the int is an odd number. An int is an even number if a division by two followed by a multiplication by two gives you back the original number (truncation of a fraction gives a smaller result for an odd number). If it is an odd number, the least significant bit is 1, otherwise it is zero. Then divide the int by 2 to get the next bit. Don't do this check-and-divide-by-two more than 31 times. Why shouldn't you do the shift more than 31 times with an int?

  4. Write another method that counts the number of “1” bits in a long value. Is there any way to share code between the two? (Hint: a long is two ints wide.) Would you do so in practice? Explain why or why not. Then look up the javadoc API and reimplement it using java.math.BigInteger.bitCount().

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.50.222