Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++에서 비트 연산자를 사용하여 숫자가 양수, 음수 또는 0인지 확인

<시간/>

여기서는 비트 연산자를 사용하여 숫자가 양수인지 음수인지 0인지 확인합니다. n>> 31과 같은 이동을 수행하면 모든 음수는 -1로, 다른 모든 숫자는 0으로 변환됩니다. -n>> 31을 수행하면 양수에 대해 -1을 반환합니다. 0에 대해 수행한 다음 n>> 31 및 -n>> 31에 대해 수행하면 둘 다 0을 반환합니다. 이를 위해 아래와 같은 다른 공식을 사용합니다 -

1+(𝑛>>31)−(−𝑛>>31)

이제 만약

  • n은 음수입니다. 1 + (-1) – 0 =0
  • n은 양수입니다. 1 + 0 – (-1) =2
  • n은 0:1 + 0 – 0 =1입니다.

예시

#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