(Intro to Java help?) Write a static method named largerDigits that accepts two
ID: 3724347 • Letter: #
Question
(Intro to Java help?)
Write a static method named largerDigits that accepts two integer parameters a and b and returns a new integer c where each digit of c gets its value from the larger of a's and b's digit in the same place. That is, the ones digit of c is the larger of the ones digit of a and the ones digit of b, and the tens digit of c is the larger of the tens digit of a and the tens digit of b, and so on. You may assume that a and b are positive integers (greater than 0).
For example, suppose a is 603452384 and b is 921782. Their digits would be combined as follows to produce c:
a 603452380
b 920784
------------------
c 952784 (return value)
Notice that if a particular digit place is absent from one number or the other, such as the 603 at the start of a above, no digit is carried over to c. The following table lists some more calls to your method and their expected return values:
Call
Value Returned
largerDigits(172, 312)
372
largerDigits(21, 3)
3
largerDigits(90, 38906735)
95
largerDigits(56002, 123321)
56322
largerDigits(11223, 4466)
4466
largerDigits(12345, 12345)
12345
largerDigits(1, 34892)
2
Hint: If you are building a result number, you may need to use Math.pow or accumulate a multiplier with each digit.
You may not use a String to solve this problem.
Call
Value Returned
largerDigits(172, 312)
372
largerDigits(21, 3)
3
largerDigits(90, 38906735)
95
largerDigits(56002, 123321)
56322
largerDigits(11223, 4466)
4466
largerDigits(12345, 12345)
12345
largerDigits(1, 34892)
2
Explanation / Answer
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// call function.
System.out.println(largerDigits(172, 312));
System.out.println(largerDigits(21,3));
System.out.println(largerDigits(90, 38906735));
System.out.println(largerDigits(56002, 123321));
System.out.println(largerDigits(11223, 4466));
System.out.println(largerDigits(12345, 12345));
System.out.println(largerDigits(1, 34892));
}
public static int largerDigits(int a,int b){
// initital variables
int i=0,large=0,digits=0;
// loop till a and b greater than zero
while(a>0 && b>0){
// check if a remainder is greater than b remainder
if(a%10>b%10){
// add remainder to first by multiplying with power of 10
large = (int)Math.pow(10,digits)*(a%10) + large;
}
else{
large = (int)Math.pow(10,digits)*(b%10) + large;
}
// increment digits
digits++;
// reduce a,b by 10
a/=10;
b/=10;
}
return large;
}
}
/*
sample output
372
3
95
56322
4466
12345
2
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.