C ++のビット演算子を使用して、数値が正、負、またはゼロかどうかを確認します
ここでは、ビット演算子を使用して、数値が正か負かゼロかを確認します。 n>> 31のようにシフトを実行すると、すべての負の数が-1に変換され、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
-
数値が正、負、または0であるかどうかを確認するPythonプログラム
数値が正、負、または0であるかどうかを確認する必要がある場合は、単純な「if」条件を使用できます。 以下は同じのデモンストレーションです- 例 my_num = 58 if my_num >= 0: if my_num == 0: print("The number is equal to zero") else: print("It is a positive number") else: &nb
-
数値が正、負、奇数、偶数、ゼロかどうかをチェックするプログラム?
数字が与えられているので、数字が偶数または奇数で正または負であることを確認する必要があります。 アルゴリズム Step 1: input number Step 2: check number is greater than equal to 0 or not. If true then positive otherwise negative and if it 0 then number is 0. Step 3: if number is divisible by 2 then it’s even otherwise its odd. サンプルコード # Python prog