Reduce a number to 1 by performing given operations | Set 3 | java program for the above approach ; Utility function to check if n is power of 2 ; Utility function to find highest power of 2 less than or equal to given number ; Recursive function to find steps needed to reduce a given integer to 1 ; Base Condition ; If the number is a power of 2 ; Else subtract the greatest power of 2 smaller than N from N ; Driver Code ; Input ; Function call
class GFG { static int highestPowerof2 ( int n ) { int p = ( int ) ( Math . log ( n ) / Math . log ( 2 ) ) ; return ( int ) Math . pow ( 2 , p ) ; } static boolean isPowerOfTwo ( int n ) { if ( n == 0 ) return false ; return ( int ) ( Math . ceil ( ( Math . log ( n ) / Math . log ( 2 ) ) ) ) == ( int ) ( Math . floor ( ( ( Math . log ( n ) / Math . log ( 2 ) ) ) ) ) ; } static int reduceToOne ( int N ) { if ( N == 1 ) { return 0 ; } if ( isPowerOfTwo ( N ) == true ) { return 1 + reduceToOne ( N / 2 ) ; } else { return 1 + reduceToOne ( N - highestPowerof2 ( N ) ) ; } } public static void main ( String [ ] args ) { int N = 7 ; System . out . println ( reduceToOne ( N ) ) ; } }