创新的方法来检查,如果数量只有一个对位有符号整数 [英] Innovative way for checking if number has only one on bit in signed int

查看:139
本文介绍了创新的方法来检查,如果数量只有一个对位有符号整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种创新的方式来检查,如果一个号码只有一个在一个有符号整数位。

我很清楚地知道,我可以简单地做一个循环与抗衡,有些模块划分,和移位。不过我很好奇,如果有一个更好的办法,因为我们只是在寻找一位要上。

 布尔HasOnlyOneBit(INT麻木)
{
   如果麻木只有一个位//返回真(IE等于1,2,4,8,16 ... Int.MinValue)
}
 

解决方案

 返回X = =(X放大器; -x);
 

这答案的作品,因为这样二进制补码的设计。

首先,一个例子。假设我们有8位有符号整数。

  00010000 = 16
11110000 = -16
 

按位,并给你 00010000 作为结果,等于原来的价值!之所以说这个作品是因为在2的补否定的时候,首先反转所有位,然后加1。你有一堆零和一帮怀揣直到此起彼伏到位。按位,然后检查是否我们有正确的位置位。

在一些情况下,其不是二的幂:

  00101010 = 42
&放大器; 11010110 = -42
----------
  00000010!= 42
 

您的结果仍然仅具有单个位,但它不会匹配原始值。因此,你的原始值多了位设置。

注意:此技术0返回真,这可能会或可能不是所希望

I'm looking for an innovative way to check if a number has only one on bit in a signed int.

I am well aware that I can simply do a loop with a counter, some modular division, and a bit shift. But I'm curious if there is a better way since we are only looking for ONE bit to be on.

bool HasOnlyOneBit (int  numb)
{
   //return true if numb has only one bit (I.E. is equal to 1, 2, 4, 8, 16... Int.MinValue)
}

解决方案

return x == (x & -x);

This answer works because of the way two's complement notation is designed.

First, an example. Assume we have 8-bit signed integers.

00010000  =  16
11110000  = -16

The bitwise and will give you 00010000 as a result, equal to your original value! The reason that this works is because when negating in 2's complement, first invert all the bits, then add 1. You'll have a bunch of zeros and a bunch of carries until a one falls into place. The bitwise and then checks if we have the right bit set.

In the case of a number that isn't a power of two:

  00101010  =  42
& 11010110  = -42
----------
  00000010 !=  42

Your result will still have only a single bit, but it won't match the original value. Therefore your original value had multiple bits set.

Note: This technique returns true for 0, which may or may not be desirable.

这篇关于创新的方法来检查,如果数量只有一个对位有符号整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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