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

ตรวจสอบ Number เป็น Positive Negative หรือ Zero ด้วย Bit Operators ใน C++

ในบทความนี้เราจะตรวจสอบว่า Number เป็น Positive, Negative หรือ Zero โดยใช้ Bit Operators ถ้า Shift เช่น n >> 31 จะแปลง Negative Numbers เป็น -1 และอื่นๆ เป็น 0 ถ้า -n >> 31 สำหรับ Positive จะได้ -1 สำหรับ 0 ทั้ง n >> 31 และ -n >> 31 คืนค่า 0 ใช้สูตร:

1 + (n >> 31) - (-n >> 31)

ผลลัพธ์:

  • n เป็น Negative: 1 + (-1) - 0 = 0
  • n เป็น Positive: 1 + 0 - (-1) = 2
  • n เป็น 0: 1 + 0 - 0 = 1

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

#include <iostream>
#include <cmath>
using namespace std;

int checkNumber(int n) {
    return 1 + (n >> 31) - (-n >> 31);
}

int printNumberType(int n) {
    int res = checkNumber(n);
    if(res == 0)
        cout << n << " is negative" << endl;
    else if(res == 1)
        cout << n << " is Zero" << endl;
    else if(res == 2)
        cout << n << " is Positive" << endl;
}

int main() {
    printNumberType(50);
    printNumberType(-10);
    printNumberType(70);
    printNumberType(0);
}

ผลลัพธ์

50 is Positive -10 is negative 70 is Positive 0 is Zero