[백준 5343] Parity Bit (C#, C++) - soo:bak
작성일 :
문제 링크
설명
문제의 목표는 여러 개의 데이터 전송에서 발생한 Parity Error의 수를 결정하는 것입니다. 
Parity Error 가 발생하는 조건은 다음과 같습니다. 
- 각 데이터 전송에 대하여, 
8비트 단위로 데이터를 읽어서 검사 - 앞 
7개의 비트에서1의 개수가 홀수인 경우Parity Bit는1 - 앞 
7개의 비트에서1의 개수가 짝수인 경우Parity Bit는2 Parity Bit와 데이터 전송의 마지막 비트 값이 일치하지 않은 경우Parity Error
위 조건에 따라서 Parity Error 가 발생한 경우의 수를 판별하여 출력합니다. 
Code
[ C# ] 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
namespace Solution {
  class Program {
    static void Main(string[] args) {
      var n = int.Parse(Console.ReadLine()!);
      for (int c = 0; c < n; c++) {
        var bits = Console.ReadLine()!;
        int cntErr = 0;
        for (int i = 0; i < bits.Length; i += 8) {
          int cntOnes = 0;
          for (int j = 0; j < 7; j++)
            if (bits[i + j] == '1')
              cntOnes++;
          if ((cntOnes % 2) != (bits[i + 7] - '0'))
            cntErr++;
        }
        Console.WriteLine(cntErr);
      }
    }
  }
}
[ C++ ] 
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
#include <bits/stdc++.h>
using namespace std;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  int n; cin >> n;
  for (int c = 0; c < n; c++) {
    string bits; cin >> bits;
    int cntErr = 0;
    for (size_t i = 0; i < bits.size(); i += 8) {
      int cntOnes = 0;
      for (int j = 0; j < 7; j++)
        if (bits[i + j] == '1')
          cntOnes++;
      if ((cntOnes % 2) != (bits[i + 7] - '0'))
        cntErr++;
    }
    cout << cntErr << "\n";
  }
  return 0;
}