Reduce a number to 1 by performing given operations | Set 3 | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int highestPowerof2 ( int n ) { int p = ( int ) log2 ( n ) ; return ( int ) pow ( 2 , p ) ; } bool isPowerOfTwo ( int n ) { if ( n == 0 ) return false ; return ( ceil ( log2 ( n ) ) == floor ( log2 ( n ) ) ) ; } 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 ) ) ; } } int main ( ) { int N = 7 ; cout << reduceToOne ( N ) << endl ; }