Binary concatenation

// I had brute forced for 1st subtask but getting run time error.
//Sample inputs are sucessfully executed.


#include <stdio.h>
#include<math.h>
#include<stdlib.h>
void decBinary(int arr[], int n);
int binaryDec(int arr[], int n);
int concat(int m, int n);
int binaryToDecimal(int n);
int main(void) {
	// your code goes here
	int t;
	scanf("%d",&t);
	while(t--){
	    int n,m,opd=0,j,p,r;
	    scanf("%d",&n);
	    int a[n],i,b[n*(n+1)/2];
	    for(i=0;i<n;i++){
	        scanf("%d",&a[i]);
	    }
//	    m=4;
//	    n=5;
	    for(i=0;i<n;i++){
	        for(j=i+1;j<n;j++){
	        p=concat(a[i],a[j]);
	      //  p=binaryToDecimal(p);
	      //  printf("%d ",p);
	        
	        r=concat(a[j],a[i]);
	      //  r=binaryToDecimal(r);
	    //    printf("%d ",r);
	         b[opd]=abs(p-r);
	        // if(opd==11)
	        // printf("%d ",b[opd]);
	         opd++;
	        }
	    }
	    int large=0;
	    for(i=0;i<opd;i++){
	        if(b[i]>large)
	        large=b[i];
	        //c[i]=binaryToDecimal(b[i]);
	    }
	    printf("%d\n",large);
	   
	   // i=concat(m,n);
	    //printf("%d",i);
	}
	return 0;
}

void decBinary(int arr[], int n) 
{ 
    int k = log2(n); 
    while (n > 0) { 
        arr[k--] = n % 2; 
        n /= 2; 
    } 
} 
  
// Funtion to convert the number 
// represented as a binary array 
// arr[] into its decimal equivalent 
int binaryDec(int arr[], int n) 
{ 
    int ans = 0; 
    for (int i = 0; i < n; i++) 
        ans += arr[i] << (n - i - 1); 
    return ans; 
} 
  
// Function to concatenate the binary 
// numbers and return the decimal result 
int concat(int m, int n) 
{ 
  
    // Number of bits in both the numbers 
    int k = log2(m) + 1; 
    int l = log2(n) + 1; 
  
    // Convert the bits in both the integers 
    // to the arrays a[] and b[] 
    int a[40] = { 0 }, b[40] = { 0 }; 
  
    // c[] will be the binary array 
    // for the result 
    int c[41] = { 0 }; 
    decBinary(a, m); 
    decBinary(b, n); 
  
    // Update the c[] array 
    int in = 0; 
    for (int i = 0; i < k; i++) 
        c[in++] = a[i]; 
    for (int i = 0; i < l; i++) 
        c[in++] = b[i]; 
  
    // Return the decimal equivalent 
    // of the result 
    return (binaryDec(c, k + l)); 
} 
int binaryToDecimal(int n) 
{ 
    int num = n; 
    int dec_value = 0; 
  
    // Initializing base value to 1, i.e 2^0 
    int base = 1; 
  
    int temp = num; 
    while (temp) { 
        int last_digit = temp % 10; 
        temp = temp / 10; 
  
        dec_value += last_digit * base; 
  
        base = base * 2; 
    } 
  
    return dec_value; 
}  
// Driver code

Did you copy the code for decBinary()? You’re supposed to give credits to GeeksforGeeks in a comment.

1 Like

I was not knowing that giving credit is mandatory so thanks for telling me.