Правила[Одномерные массивы]45. Дан массив, состоящий из n натуральных чисел. Образовать новый массив, элементами которого будут элементы исходного, оканчивающиеся на цифру k.
public static int[] endsByK (int[] arr, int k){
if (k < 0)
return new int[0];
int count = 0;
for (int n : arr) {
if (Math.abs(n) % 10 == k)
count++;
}
int[] res = new int[count];
count = 0;
for (int n : arr) {
if (Math.abs(n) % 10 == k)
res[count++] = n;
}
return res;
}
<code>public static int[] arrayOfK(int k, int... array) {
int[] temp = new int[0];
String sK = String.valueOf(k);
for (int x : array) {
String sX = String.valueOf(x);
if (sX.endsWith(sK)) {
temp = Arrays.copyOf(temp, temp.length + 1);
temp[temp.length - 1] = x;
}
}
return temp;
}</code>
Насколько я пока понял, с обычными массивами будем работать редко, скорее использоваться будут списки, так как они быстрее всего. И утруждать код двумя циклами перебора одного и того же для задания длины не особо нужно. Если это не так, пожалуйста объясните или киньте какую нибудь авторитетную (конечно же на ваш взгляд) ссылку. Очень благодарен.
public static int[] newArrayWithLastK (int[] array, int k) {
if (k < 0) {
System.out.print("k is " + k + ", k must be greater than 0!");
return new int[0];
}
int count = 0;
for (int i = 0; i < array.length; i++) {
if (Integer.toString(array[i]).endsWith(Integer.toString(k))) {
count++;
}
}
System.out.println(count);
int[] newArr = new int[count];
count = 0;
for (int i = 0; i < array.length; i++) {
if (Integer.toString(array[i]).endsWith(Integer.toString(k))) {
newArr[count++] = array[i];
}
}
return newArr;
}
public static int[] solve(int[] arr, int k) {
int n = arr.length;
int count = 0;
for (int i = 0; i < n; i++) {
if (Integer.toString(i).endsWith(Integer.toString(k))) {
count++;
}
}
int[] res = new int[count];
count = 0;
for (int i = 0; i < n; i++) {
if (Integer.toString(i).endsWith(Integer.toString(k))) {
res[count++] = arr[i];
}
}
return res;
}
ПЕРЕЙДИТЕ В ПОЛНУЮ ВЕРСИЮ