The Java class Zillion uses a private array of int\'s called digits to hold the
ID: 3836262 • Letter: T
Question
The Java class Zillion uses a private array of int's called digits to hold the digits of a non-negative integer. Each element of digits is an int from 0 to 9. For example, if digits has length 4, then it represents 175 like this; the small numbers are its indexes.
0175
Suppose we want to multiply the integer in digits by ten. We discard its leftmost element, shift its other elements one place to the left, and add a new element 0 on its right. If we do this to the digits array shown above, then it looks like this:
1750
Write a public method for the class Zillion called timesTen. It must multiply the integer in digits by ten, in the way described above. It must take no arguments, and return no value. It need not test if an integer is too big for digits after multiplication. Your timesTen method must work for any digits array, of any length, not just the one shown in the example!
Explanation / Answer
Here is the code for Zillion.java:
class Zillion
{
int[] digits;
//public Zillion(int size)
//Constructor. Create a private array of size integers (int’s). You may assume that size
//is greater than or equal to 0. You need not initialize the array, because Java
//initializes all the elements to 0 for you.
public Zillion(int size)
{
digits = new int[size];
}
//public void increment()
//Increment the counter, using the algorithm described in part 2. One way to do that is
//by using a while loop; there may be other ways. If the counter contains all 9’s, then
//you must not generate an illegal array index.
public void increment()
{
for(int i = digits.length-1; i >= 0; i--)
{
digits[i]++;
if(digits[i] < 10)
break;
digits[i] = 0;
}
}
//public String toString()
//Convert the digits in the counter to a String, and return that String. One way to do
//that is by using a for loop that concatenates all the digits of the array together
//using the operator +. Note that Java automatically converts an integer to a string
//when you concatenate it.
public String toString()
{
String output = "";
for(int i = 0; i < digits.length; i++)
output += digits[i];
return output;
}
//public void timesTen()
//It must multiply the integer in digits by ten, in the way described above. It must take
//no arguments, and return no value. It need not test if an integer is too big for digits
//after multiplication. Your timesTen method must work for any digits array, of any length,
//not just the one shown in the example!
public void timesTen()
{
for(int i = 1; i < digits.length; i++)
digits[i-1] = digits[i]; //Move the digits to the left.
digits[digits.length-1] = 0;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.