Nearest smaller power of 2 for every digit of a number | C ++ program to implement the above approach ; Function to find the nearest power of two for every digit of a given number ; Converting number to string ; Traverse the array ; Calculate log base 2 of the current digit s [ i ] ; Highest power of 2 <= s [ i ] ; ASCII conversion ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void highestPowerOfTwo ( int num ) { string s = to_string ( num ) ; for ( int i = 0 ; i < ( int ) s . size ( ) ; i ++ ) { if ( s [ i ] == '0' ) { cout << "0" ; continue ; } int lg = log2 ( int ( s [ i ] ) - 48 ) ; int p = pow ( 2 , lg ) ; cout << char ( p + 48 ) ; } } int main ( ) { int num = 4317 ; highestPowerOfTwo ( num ) ; return 0 ; }