Algorithm
Problem Name: beecrowd | 2176
Problem Link: https://www.beecrowd.com.br/judge/en/problems/view/2176
Parity
By Cristhian Bonilha, UTFPR Brazil
Timelimit: 1
The popularity of WiFi networks increased the loss rate of data being transferred, as several environment factors can easily compromise the data during traffic. The main goal of URI, Unity of Recovery of Information, is to identify and correct errors in messages being sent through WiFi networks.
The technique used by URI to identify errors is the parity test, which can be described as follows: Be S a message that is going to be sent from one device to another. Before S is sent, an extra bit B is added to the end of the binary representation of S. If S has an even number of bits of value 1, the extra bit B will have value 0. Otherwise, if S has an odd number of bits of value 1, B will have value 1. In this way, after the insertion of the bit B, the message S will have an even number of bits of value 1.
When the receiver gets the message S he counts how many bits of value 1 the message has. If the quantity is even, it means that the message was transferred succesfully. Otherwise, it means that the message had a modification and is not correct.
Your task is to write an algorithm that makes the insertion of the extra bit B in the message S, ensuring that after the insertion the message S has an even number of bits of value 1.
Input
Each test case consists of one line containing the message S, which has at least 1 and at most 100 bits.
Output
Print one line containing the message S with the extra bit B.
Input Samples | Output Samples |
10 |
101 |
000110 |
0001100 |
0 |
00 |
Code Examples
#1 Code Example with C Programming
Code -
C Programming
#include <stdio.h>
int main(void)
{
char str[1000000];
int i, j=0, x;
fgets(str, 1000000, stdin);
for (i=0; str[i]!=0; ++i)
{
if (str[i]=='1')
++j;
printf("%c", str[i]);
}
if (j%2==0)
printf("0\n");
else
printf("1\n");
return 0;
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with C++ Programming
Code -
C++ Programming
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
cin >> s;
int c = 0;
for(int i = 0 ; i < s.length() ; i++){
if(s[i] == '1') c++;
}
if(c % 2 == 0) cout << s << 0 << endl;
else cout << s << 1 << endl;
return 0;
}
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var lines = input.split('\n');
let number = lines.shift().trim();
let cont = 0;
for(let i = 0; i < number.length; i++){
if(number[i] == 1){
cont++;
}
}
if(cont % 2 != 0){
console.log(number + 1);
}
else{
console.log(number + 0);
}
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with Python Programming
Code -
Python Programming
message = input()
one = 0
for i in message:
if i == '1':
one += 1
print(message + str(one % 2))
Copy The Code &
Try With Live Editor
Input
Output