Find the sum of all array elements that are equidistant from two consecutive powers of 2 | Java program for the above approach ; Function to print the sum of array elements that are equidistant from two consecutive powers of 2 ; Stores the resultant sum of the array elements ; Traverse the array arr [ ] ; Stores the power of 2 of the number arr [ i ] ; Stores the number which is power of 2 and lesser than or equal to arr [ i ] ; Stores the number which is power of 2 and greater than or equal to arr [ i ] ; If arr [ i ] - LesserValue is the same as LargerValue - arr [ i ] ; Increment res by arr [ i ] ; Return the resultant sum res ; Driver Code
class GFG { static int FindSum ( int [ ] arr , int N ) { int res = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int power = ( int ) ( Math . log ( arr [ i ] ) / Math . log ( 2 ) ) ; int LesserValue = ( int ) Math . pow ( 2 , power ) ; int LargerValue = ( int ) Math . pow ( 2 , power + 1 ) ; if ( ( arr [ i ] - LesserValue ) == ( LargerValue - arr [ i ] ) ) { res += arr [ i ] ; } } return res ; } public static void main ( String [ ] args ) { int [ ] arr = { 10 , 24 , 17 , 3 , 8 } ; int N = arr . length ; System . out . println ( FindSum ( arr , N ) ) ; } }