DEV Community

Discussion on: Challenge: Get Closest Number in an Array

Collapse
 
hpj1992 profile image
Harshit • Edited

Java:

        int[] nums = {100, 200, 400, 800, 1600, 3200, 6400, 128000};
        int ans = 0;
        int given_num = 900;
        int minDistance = Integer.MAX_VALUE;
        for (int i =0; i < nums.length; i++) {
            int curDistance = Math.abs(nums[i] - given_num);
            if (curDistance < minDistance) {
                ans = nums[i];
                minDistance = curDistance;
            }
        }
        System.out.println(ans);

Trying to optimize no of lines with Java 8 Streams and Lambda.