Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Kiểm tra số dương, âm hay 0 bằng toán tử bit trong C++


Kiểm tra dấu của số nguyên dùng toán tử bit. Dịch phải 31 bit: n >> 31 biến số âm thành -1, các số khác thành 0. -n >> 31 biến số dương thành -1. Với 0, cả hai đều trả 0.

Công thức: 1 + (n >> 31) - (-n >> 31)

  • n âm: 1 + (-1) - 0 = 0
  • n dương: 1 + 0 - (-1) = 2
  • n = 0: 1 + 0 - 0 = 1

Ví dụ

#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);
}

Kết quả

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