每日一练104——Java找到可以被给定数字整除的数字(8kyu)

题目

编写一个函数,它接受两个参数并返回所有可被给定除数整除的数字。第一个参数是数字数组,第二个参数是除数。

divisibleBy([1,2,3,4,5,6], 2) == [2,4,6]
divisibleBy([1,2,3,4,5,6], 2) == [2,4,6]

测试用例

import java.util.Arrays;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import org.junit.Test;
public class EvenNumbersTest
{

    @Test 
    public void testSimple()
    {
        assertTrue(Arrays.equals(new int[] {2,4,6}, EvenNumbers.divisibleBy(new int[] {1,2,3,4,5,6},2)));
        assertTrue(Arrays.equals(new int[] {3,6}, EvenNumbers.divisibleBy(new int[] {1,2,3,4,5,6},3)));
        assertTrue(Arrays.equals(new int[] {0,4}, EvenNumbers.divisibleBy(new int[] {0,1,2,3,4,5,6},4)));
    }
}

解题

My

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class EvenNumbers {
    public static int[] divisibleBy(int[] numbers, int divider) {
        List arrayList = new ArrayList<>();
        for (int number : numbers) {
            if (number % divider == 0) {
                arrayList.add(number);
            }
        }
        int[] newNumbers = new int[arrayList.size()];
        for (int i = 0; i 

Other

import java.util.stream.*;
import java.util.Arrays;

public class EvenNumbers {
  public static int[] divisibleBy(int[] numbers, int divider) {
  
    return Arrays.stream(numbers)
                 .filter(i -> (i % divider) == 0)
                 .toArray();
  }
}

后记

ArrayList我也是第一次用。

你可能感兴趣的:(每日一练104——Java找到可以被给定数字整除的数字(8kyu))