Count of numbers which can be made power of 2 by given operation in C++

C++Server Side ProgrammingProgramming

We are given an array of positive integers. The goal is to find the count of numbers that can be made power of two by adding 1 to them utmost once.

We will check using log2(i) that number is power of two or can become power of two by adding 1 to it. If yes increment count.

Let’s understand with examples.

Input − arr[]= {1,3,2,5,6 },

Output − Count of numbers that can become power of 2: 3

Explanation − 1+1=2 → 21 , 3+1=4 → 22 , 2=21 others will become 5+1=6, 6+1=7

Input − arr[]= {2,4,8,16 },

Output− Count of numbers that can become power of 2: 4

Explanation − All 4 numbers are already power of 2.

Approach used in the below program is as follows

  • We take an integer array arr[] initialized with random positive numbers.

  • Function powofTwo(int arr[],int n) takes an array and its length as input and returns a count of numbers that are or can be made power of two.

  • Take the initial count as 0.

  • Traverse array from i=0 to i<n.

  • For each element check if floor(log2(arr[i]))==ceil((log2(arr[i])) or floor(log2(arr[i]+1))==ceil((log2(arr[i]+1)) , if true increment count in both cases.

  • Return count as final result.

Example

 Live Demo

#include <bits/stdc++.h>
#include <math.h>
using namespace std;
int powofTwo(int arr[],int n){
   int count=0;
   for(int i=0;i<n;i++){
      if( floor(log2(arr[i])) == ceil(log2(arr[i])) )
         { count++; }
      else{
         ++arr[i];
         if( floor(log2(arr[i])) == ceil(log2(arr[i])) )
            { count++; }
      }
   }
   return count;
}
int main(){
   int Arr[]={ 5,6,9,3,1 };
   int len=sizeof(Arr)/sizeof(Arr[0]);
   cout<<endl<<"Count of numbers with power of 2 possible: "<<powofTwo(Arr,len);
   return 0;
}

Output

If we run the above code it will generate the following output −

Count of numbers with power of 2 possible: 2
raja
Published on 31-Aug-2020 08:23:21
Advertisements