使用 C++ 中的按位運算子檢查某個數字是正數、負數還是零
這裡我們將使用按位運算子來檢查一個數字是正數、負數還是零。如果我們執行移位,例如 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP