Implement the following two static methods. Note that, although the two methods
ID: 3930374 • Letter: I
Question
Implement the following two static methods. Note that, although the two methods compute the same function, the first one clears the givenNaturalNumber while the second one restores it.
/**
* Returns the product of the digits of {@code n}.
*
* @param n
* {@code NaturalNumber} whose digits to multiply
* @return the product of the digits of {@code n}
* @clears n
* @ensures productOfDigits1 = [product of the digits of n]
*/
private static NaturalNumber productOfDigits1(NaturalNumber n) {...}
/**
* Returns the product of the digits of {@code n}.
*
* @param n
* {@code NaturalNumber} whose digits to multiply
* @return the product of the digits of {@code n}
* @ensures productOfDigits2 = [product of the digits of n]
*/
private static NaturalNumber productOfDigits2(NaturalNumber n) {...}
/**
* Returns the product of the digits of {@code n}.
*
* @param n
* {@code NaturalNumber} whose digits to multiply
* @return the product of the digits of {@code n}
* @clears n
* @ensures productOfDigits1 = [product of the digits of n]
*/
private static NaturalNumber productOfDigits1(NaturalNumber n) {...}
Explanation / Answer
Hi, Please find my implementation.
Please let me know in case of any issue.
Hi, you have not given the structure of class NaturalNumber
I am assuming that NaturalNumber class has one method : getNumber() and setNumber(int num)
1)
/**
* Returns the product of the digits of {@code n}.
*
* @param n
* {@code NaturalNumber} whose digits to multiply
* @return the product of the digits of {@code n}
* @clears n
* @ensures productOfDigits1 = [product of the digits of n]
*/
private static NaturalNumber productOfDigits1(NaturalNumber n) {
int number = n.getNumber();
if(number == 0)
return 0;
int mul = 1;
while(number > 0){
mul = mul*(number/10);
number = number/10;
}
return mul;
}
2)
/**
* Returns the product of the digits of {@code n}.
*
* @param n
* {@code NaturalNumber} whose digits to multiply
* @return the product of the digits of {@code n}
* @ensures productOfDigits2 = [product of the digits of n]
*/
private static NaturalNumber productOfDigits2(NaturalNumber n) {
int number = n.getNumber();
if(number == 0)
return 0;
int mul = 1;
while(number > 0){
mul = mul*(number/10);
number = number/10;
}
// crearing NaturalNumber
n.setNumber(0);
return mul;
}