使用 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