FindTheNumberClosestToZero

import org.junit.Test; public class BetterProgrammer05122012Test extends junit.framework.TestCase { public static int[] numbers = new int[] {5, 10, -5, 0, 25, 35}; public static int[] numbers2 = new int[] {5, 10, -5, -2, 0, 25, 35}; public static int[] noNegativeNumbers = new int[] {5, 10, 15, 25, 35}; @Test public void testBetterProgrammer05122012 () { assertEquals(5, BetterProgrammer05122012.getSumOfTwoClosestToZeroElements(numbers)); } @Test public void testArrayWithNegativeNumberLowest () { assertEquals(2, BetterProgrammer05122012.getSumOfTwoClosestToZeroElements(numbers2)); } @Test public void testArrayWithNoNegativeNumbers() { assertEquals(5, BetterProgrammer05122012.getSumOfTwoClosestToZeroElements(noNegativeNumbers)); } } import java.util.Arrays; public class BetterProgrammer05122012 { public static int getSumOfTwoClosestToZeroElements(int[] a) { /* Please implement this method to return the sum of the two elements closest to zero. If there are two elements equally close to zero like -2 and 2, consider the positive element to be "closer" to zero than the negative one. */ int[] b = a; Arrays.sort(b); int negativeValuePlacement = 0; int positiveValuePlacement = 0; int closestNumberToZero; for( int i = 0; i < b.length; i++) { if (b[i] < 0) {negativeValuePlacement++; positiveValuePlacement++; } if (b[i] == 0) positiveValuePlacement++; } --negativeValuePlacement; if (b[0] >= 0) closestNumberToZero = b[positiveValuePlacement]; else { if ((b[negativeValuePlacement]*-1) < b[positiveValuePlacement]) { closestNumberToZero = (b[negativeValuePlacement]*-1); } else closestNumberToZero = b[positiveValuePlacement]; } return closestNumberToZero; } }
This program finds the number in an array that's closest to zero.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.