JavaRush/Java блог/Архив info.javarush/Кухня(); Задание N12.
terranum
28 уровень

Кухня(); Задание N12.

Статья из группы Архив info.javarush
участников
Кухня(); Задание N12. - 1 Правила [Одномерные массивы] 12. Даны натуральные числа a1, a2, ..., an. Указать те, у которых остаток от деления на М равен L (0 ≤ L ≤ М – 1).
Комментарии (11)
  • популярные
  • новые
  • старые
Для того, чтобы оставить комментарий Вы должны авторизоваться
RabenokDmitry
Уровень 21
10 февраля 2015, 00:23
public static int[] modulo(int[] array, int m, int l) {
        int[] result = new int[0];
        for (int value : array) {

            System.out.print(value % m == l ? value + "\n" : "");
            if (value % m == l) {

                result = Arrays.copyOf(result, result.length + 1);
                result[result.length - 1] = value;
            }
        }
        return result;
    }
Voronblack
Уровень 17
24 августа 2014, 22:19
Добавил некоторые ограничения на деление, а остальное все с той же второй кухни.
public static int[] divideWithRemainder(int m, int l, int...values)
    {
        if(values.length == 0 || m == 0)
        throw new IllegalArgumentException("Bad args");

        int[] result = new int[0];
        for (int i : values)
            if(i % m == l)
            {
            result = Arrays.copyOf(result, result.length + 1);
            result[result.length - 1] = i;
            }
        return result;
    
    }
terranum
Уровень 28
24 августа 2014, 22:27
По красоте все! :)
Sultan
Уровень 16
24 августа 2014, 20:50

public static int[] method(int[] arr, int m, int l) {
    LinkedList<int> res = new LinkedList<int>();
    for (int n : arr) {
        if (n % m == l) {
            res.add(n);
        }
    }
    return res.toArray();
}
Docktor91
Уровень 40
24 августа 2014, 21:01
LinkedList<int>

Integer нужно, примитив же…
Sultan
Уровень 16
24 августа 2014, 21:06

public static int[] method(int[] arr, int m, int l) {
    LinkedList<Integer> res = new LinkedList<Integer>();
    for (int n : arr) {
        if (n % m == l) {
            res.add(n);
        }
    }
    return res.toArray();
}
Docktor91
Уровень 40
24 августа 2014, 21:10
кароче чтобы все работало нужно так
public static Integer[] method(int[] arr, int m, int l) {
        LinkedList<Integer> res = new LinkedList<Integer>();
        for (int n : arr) {
            if (n % m == l) {
                res.add(n);
            }
        }
        return res.toArray(new Integer[res.size()]);
    }
Sultan
Уровень 16
24 августа 2014, 21:14
Обоснуй
Docktor91
Уровень 40
24 августа 2014, 21:18
res.toArray()- возвращает Object[]
заявленный тип int[]
чтобы вернуть Integer[] воспользуемся
res.toArray(T[] a) T-дженерик
Sultan
Уровень 16
24 августа 2014, 21:24
ну ок
terranum
Уровень 28
24 августа 2014, 22:29
Читернули с листами)