Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม

การตรวจสอบ Parity (คู่/คี่) ของตัวเลข

บทนำ

Parity (ความคู่คี่) ของตัวเลขขึ้นอยู่กับจำนวน 1 ที่ปรากฏในค่า Binary เทียบเท่าของตัวเลขนั้น เมื่อจำนวน 1 เป็นคี่ จะคืนค่า Odd Parity สำหรับจำนวน 1 เป็นคู่ จะคืนค่า Even Parity

เนื่องจากตัวเลขในหน่วยความจำคอมพิวเตอร์เก็บในรูป Binary เราจึงสามารถเลื่อนบิต (Shift Bits) ได้ง่าย ในกรณีนี้ ด้วยการเลื่อนบิต เราจะนับจำนวน 1 ที่ปรากฏใน Binary ของตัวเลขที่กำหนด

อินพุตและเอาต์พุต

Input: ตัวเลข: 5, Binary คือ (101)
Output: Parity of 5 is Odd.

อัลกอริทึม

finParity(n)
Input: ตัวเลข n
Output: ตรวจสอบว่าตัวเลขมี Even Parity หรือ Odd Parity

Begin
    count := 0
    temp := n
    while temp >= 2, do
        if temp มี 1 เป็น LSb, then
            count := count + 1
        temp := right shift temp 1 bit
    done
    if count เป็นเลขคี่, then
        display เป็น odd parity
    else
        display even parity
End

ตัวอย่างโค้ด (C++)

#include <iostream>
using namespace std;

bool findParity(int n) {
    int count = 0;
    int temp = n;
    while (temp >= 2) {
        if (temp & 1)  // เมื่อ LSb เป็น 1 เพิ่ม count
            count++;
        temp = temp >> 1;  // right shift ตัวเลข 1 บิต
    }
    return (count % 2) ? true : false;
}

int main() {
    int n;
    cout << "Enter a number: "; cin >> n;
    cout << "Parity of " << n << " is " << (findParity(n) ? "Odd" : "Even");
}

ผลลัพธ์

Enter a number: 5
Parity of 5 is Odd