ที่นี่เราจะตรวจสอบว่าตัวเลขเป็นบวกหรือลบหรือศูนย์โดยใช้ตัวดำเนินการบิต หากเราทำการขยับเช่น 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