Encrypt Data by Inverting Bits - Coding Problem & Solutions
Problem - Encrypt Data by Inverting Bits
A company is transmitting its data to a new server. There are $N$ files, each containing numeric data. Before being transmitted, the data is encrypted by converting it into its binary form, inverting the bits, and then converting the new binary value back into a decimal number. Write an algorithm to encrypt the data as per the given requirements.
Input / Output Formats:
Input Format: The first line consists of an integer representing the number of data entries ($N$). The last line consists of $N$ space-separated integers representing the data to be encrypted.
Output Format: Print $N$ space-separated integers representing the encrypted data of each file.
Example
Input:
4
65 29 56 34
Output: 62 2 7 29
Solution in:
import java.util.Scanner;
public class EncryptData {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int data[] = new int[n];
for(int i=0; i<n; i++){
data[i] = sc.nextInt();
}
int encryptedData[] = new int[n];
for(int i=0; i<n; i++){
String binary = Integer.toBinaryString(data[i]);
String binaryInvert = "";
for(int j=0; j<binary.length(); j++){
if(binary.charAt(j)=='0'){
binaryInvert += '1';
}else{
binaryInvert += '0';
}
}
encryptedData[i] = Integer.parseInt(binaryInvert, 2);
}
for(int i=0; i<n; i++){
System.out.print(encryptedData[i]);
if(i < n-1){
System.out.print(" ");
}
}
}
}
n = int(input())
data = list(map(int, input().split()))[:n]
result = []
for ele in data:
result.append(ele ^ int("1" * len(bin(ele)[2:]), 2))
print(*result)