检查一个数字是当使用C位运算符非零 [英] Check if a number is non zero using bitwise operators in C

查看:372
本文介绍了检查一个数字是当使用C位运算符非零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查是否一个数 X 为非零使用合法经营,除了

Check whether a number x is nonzero using the legal operators except !.

例如: isNonZero(3)= 1 isNonZero(0)= 0

法律OPS: &安培; ^ | + << >>

Legal ops: ~ & ^ | + << >>


  • 注:只有位运算符应使用。 如果其他等,不能用

  • EDIT1:运营商的号应该不超过10

  • EDIT2:考虑 INT 的大小为4个字节

  • Note : Only bitwise operators should be used. if, else, for, etc. cannot be used.
  • Edit1 : No. of operators should not exceed 10.
  • Edit2 : Consider size of int to be 4 bytes.

int isNonZero(int x) {
return ???;
}

使用这将是微不足道的,但是我们如何做到这一点,而无需使用

Using ! this would be trivial , but how do we do it without using ! ?

推荐答案

在adamk函数的版本数:

The logarithmic version of the adamk function:

int isNotZero(unsigned int n){
  n |= n >> 16;
  n |= n >> 8;
  n |= n >> 4;
  n |= n >> 2;
  n |= n >> 1;
  return n & 1;
};

和最快的国家之一,但在装配:

And the fastest one, but in assembly:

xor eax, eax
sub eax, n  // carry would be set if the number was not 0
xor eax, eax
adc eax, 0  // eax was 0, and if we had carry, it will became 1

相似的程序集的版本的东西,可以用C写的,你只要有符号位,有一些差异玩了。

Something similar to assembly version can be written in C, you just have to play with the sign bit and with some differences.

编辑:这是我能想到的在C最快的版本:

here is the fastest version I can think of in C:

1)为负数:如果符号位被设置,则数目不为0

1) for negative numbers: if the sign bit is set, the number is not 0.

2)阳性: 0 - N 将negaive,可以作为检查的情况下,1。我不看 - 在法律操作的列表,因此我们将使用〜N + 1 来代替。

2) for positive: 0 - n will be negaive, and can be checked as in case 1. I don't see the - in the list of the legal operations, so we'll use ~n + 1 instead.

我们得到:

int isNotZero(unsigned int n){ // unsigned is safer for bit operations
   return ((n | (~n + 1)) >> 31) & 1;
}

这篇关于检查一个数字是当使用C位运算符非零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆