Skip to content

Instantly share code, notes, and snippets.

@jsbonso
Created October 17, 2017 05:56
Show Gist options
  • Save jsbonso/99f1c5bc615b17a622eb56e439caac41 to your computer and use it in GitHub Desktop.
Save jsbonso/99f1c5bc615b17a622eb56e439caac41 to your computer and use it in GitHub Desktop.
Java - Checks if the number is a sum of any of the 2 numbers in the list
import java.util.Arrays;
public class App {
public static void main( String[] args ) {
int[] inArray = {1, 3, 3, 5, 7};
int baseNum = 6;
System.out.println("Number List: " + Arrays.toString(inArray) );
// Should return true
// as the sum of the 2nd and 3rd element is 6.
System.out.println( baseNum + " is a sum of any 2 numbers in the list: " + hasBaseNumberAsSum(inArray, baseNum) );
baseNum = 14;
// Should return false.
// The element should not be added by itself,
// that's why even if last element is (7 + 7 = 14),
// it should return false as that adding by itself if invalid.
System.out.println( baseNum + " is a sum of any 2 numbers in the list: " + hasBaseNumberAsSum(inArray, baseNum) );
// Should return true
// As the sum of the 3rd and fourth element is 8
baseNum = 8;
System.out.println( baseNum + " is a sum of any 2 numbers in the list: " + hasBaseNumberAsSum(inArray, baseNum) );
}
/**
* Determines if the given baseNum is a sum of any of the numbers in the inArray,
* excluding the number itself.
*
* @param inArray
* @param baseNum
* @return
*/
static boolean hasBaseNumberAsSum(int[] inArray, int baseNum){
for (int i=0; i < inArray.length; i++){
for (int j=0; j < inArray.length; j++){
// skip if the index is the same, so it won't check the sum of itself.
if ( i == j)
continue;
// check if the sum of the 2 separate numbers is equals the given baseNum
if ( (inArray[i] + inArray[j] == baseNum))
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment