Question:
How to write a java program that 4 ints have been provided as input. Return true if the sum of any two of them is a power of 2.?
Code:
public class TestSums { public static void main(String[] args) { int vars[] = new int[args.length]; for(int n=0;n<vars.length;n++){ try { vars[n]= Integer.parseInt(args[n]); } catch (NumberFormatException e) { System.out.println(args[n] + " is no a number."); } } for(int i=0;i<vars.length;i++){ for(int j=i+1;j<vars.length;j++){ System.out.print(vars[i] + "," + vars[j] + ": " ); System.out.println(sumIsPowerOfTwo(vars[i],vars[j])); } } } static boolean sumIsPowerOfTwo(int x, int y) { int z = x + y; return ((z & (z -1)) == 0); } }
Output:
$ java TestSums 2 4 6 8 2,4: false 2,6: true 2,8: false 4,6: false 4,8: false 6,8: false