closest Integer - Java java.lang

Java examples for java.lang:int

Description

closest Integer

Demo Code


//package com.java2s;

public class Main {
    public static int closestInteger(int source, int[] target) {
        if (target == null || target.length == 0)
            return source;
        int minDelta = Integer.MAX_VALUE, result = source;
        for (int t : target) {
            int delta = Math.abs(source - t);
            if (delta < minDelta) {
                minDelta = delta;/*from w  w  w . j a  v a  2 s  .  c  o  m*/
                result = t;
            }
        }
        return result;
    }
}

Related Tutorials