Sorry if I type something wrong, I am new. I want to create a method that takes an array, and gives back an array with the numbers that have the same first and last digits in the previous array.I want to use System.out in the Main(other) class.
I have created this for loop to go through the numbers, but I don’t know how to compare them.
public int[] findDuplicates(int[] a) {
List<Integer> result = new ArrayList<>();
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if ((//what do I write here) ) {
//and here
}
}
}
return result.stream()
.mapToInt(Integer::intValue)
.toArray();
}
>Solution :
The easiest way is to parse your numbers into strings and compare them. I did it this way :
public int[] findDuplicates(int[] a) {
List<Integer> result = new ArrayList<>();
boolean[] numbersThatHaveBeenAdded = new boolean[a.length];
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
String iNumber = String.valueOf(a[i]);
String jNumber = String.valueOf(a[j]);
if (iNumber.charAt(0) == jNumber.charAt(0)
&& iNumber.charAt(iNumber.length()-1) == jNumber.charAt(jNumber.length()-1)) {
if (!numbersThatHaveBeenAdded[i]) {
result.add(a[i]);
numbersThatHaveBeenAdded[i] = true;
}
if (!numbersThatHaveBeenAdded[j]) {
result.add(a[j]);
numbersThatHaveBeenAdded[j] = true;
}
}
}
}
return result.stream()
.mapToInt(Integer::intValue)
.toArray();
}
And I used a boolean array to keep in memory the numbers I already added in the result, to avoid duplication.