Get array by doubling or adding 1
Problem : Get the array as given in input from set of array of same size of input with all values 0.
Operations can be performed : You can add 1 to one element in an array and double whole array
Idea:Here we will add 1 into count if array is having odd value .
We will add 1 to count and divide whole array by 2 if all entries in array are even.
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static int count(int [] arr,int n)
{
int countval=0;
while(true)
{
int zerocount=0;
int i=0;
for(i=0;i<n;i++)
{
if(arr[i]%2==1)
break;
if(arr[i]==0)
zerocount++;
}
if(zerocount==n)
return countval;
if(i==n)
{
for(int j=0;j<n;j++)
arr[j]=arr[j]>>1;
countval++;
}
for(int j=i;i<n;i++)
{
if(arr[j]%2==1)
{
arr[j]--;
countval++;
}
}
}
}
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
int n=ab.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
arr[i]=ab.nextInt();
System.out.println(count(arr,n));
}
}
}
0 Comments:
Post a Comment