In: Computer Science
This question concerns the construction of a NumberUtils class declaration that contains a collection of useful routines. Write a class declaration that satisfies the following specification: Class NumberUtils The NumberUtils class contains a collection of routines for working with integers. Instance variables None Constructors private NumberUtils() {} // A private, empty-bodied constructor prevents NumberUtil objects from being created. Methods public static int[] toArray(int number) // Given a number that is n digits in length, maps the digits to an array length n. // e.g. given the number 5678, the result is the array {5, 6, 7, 8}. public static int countMatches(int numberA, int numberB) // Given two numbers, count the quantity of matching digits – those with the same value and // position. For example, given 39628 and 79324, there are 2 digits in common: x9xx2x. // It is assumed that the numbers are the same length and have no repeating digits. public static int countIntersect(int numberA, int numberB) // Count the quantity of digits that two numbers have in common, regardless of position. // For example, given 39628 and 97324, there are 3 digits in common: 3, 7, 2. // It is assumed that the numbers are the same length and have no repeating digits. You should make a simple test program (which you do not need to submit) to check your code.
PLEASE GIVE IT A THUMBS UP, I SERIOUSLY NEED ONE, IF YOU NEED ANY MODIFICATION THEN LET ME KNOW, I WILL DO IT FOR YOU
class NumberUtils {
private NumberUtils() {
//preventing object creation
}
public static int[] toArray(int number) {
String num = String.valueOf(number);
int length = num.length();
int arr[] = new int[length];
for (int i = 0; i < length; i++) {
arr[i] = Integer.parseInt(Character.toString(num.charAt(i)));
}
return arr;
}
public static int countMatches(int numberA, int numberB) {
String n1 = String.valueOf(numberA);
String n2 = String.valueOf(numberB);
int len = n1.length(), count = 0; // as mentioned, length of both is same. we can take length of any
for (int i = 0; i < len; i++) {
if (n1.charAt(i) == n2.charAt(i)) {
count++;
}
}
return count;
}
public static int countIntersect(int numberA, int numberB) {
String n1 = String.valueOf(numberA);
String n2 = String.valueOf(numberB);
int len = n1.length(), count = 0; // as mentioned, length of both is same. we can take length of any
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
if (n1.charAt(i) == n2.charAt(j)) {
count++;
}
}
}
return count;
}
// just for testing, please remove as this is not required as per the program
public static void main(String[] args) {
System.out.println("Testing toArray ->");
for (int i = 0; i < toArray(5678).length; i++) {
System.out.print(toArray(5678)[i] + " ");
}
System.out.println();
System.out.println("Testing countMatches ->");
System.out.println(countMatches(39628, 79324));
System.out.println("Testing countIntersect ->");
System.out.println(countIntersect(39628, 97324));
}
}