-
Notifications
You must be signed in to change notification settings - Fork 0
/
SCTDL009.cpp
64 lines (55 loc) · 1.09 KB
/
SCTDL009.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* @file SCTDL009.cpp
* @author long ([email protected])
* @brief Gray code to Binary
* @version 0.1
* @date 2023-03-18
*
* @copyright Copyright (c) 2023
*
*/
// C++ program for Binary To Gray
// and Gray to Binary conversion
#include <iostream>
using namespace std;
// Helper function to xor two characters
char xor_c(char a, char b)
{
return (a == b) ? '0' : '1';
}
// Helper function to flip the bit
char flip(char c)
{
return (c == '0') ? '1' : '0';
}
// function to convert gray code string
// to binary string
string graytoBinary(string gray)
{
string binary = "";
// MSB of binary code is same as gray code
binary += gray[0];
// Compute remaining bits
for (int i = 1; i < gray.length(); i++) {
// If current bit is 0, concatenate
// previous bit
if (gray[i] == '0')
binary += binary[i - 1];
// Else, concatenate invert of
// previous bit
else
binary += flip(binary[i - 1]);
}
return binary;
}
int main()
{
int t;
cin >> t;
while(t--) {
string gray;
cin >> gray;
cout << graytoBinary(gray) << endl;
}
return 0;
}