几种求32位数中1的个数的算法

方法一:最简单的循环位运算

int count1(int i)
{
    int num=0;
    while(i!=0) 
    {
        num += i & 0x01;
        i >>>= 1;
    }
    return num;
}

时间复杂度是O(n),且n一定是32。

方法二:n&(n-1)

int count2(int i) 
{
    int num = 0;
    while(i!=0) {
        i &= (i-1);
        num++;
    }
    return num;
}

时间复杂度也是O(n),但只有在最坏情况下n才为32

方法三:查表发

查表发利用空间换取时间,利用一个32位的数组存储0~2^32的数每个数字的1的位数,利用arr[n]即可得到结果,时间复杂度为O(1),但是空间复杂度为O(2^n)。一般情况下不会使用一个大表直接查询,而是将32位拆分成4个8位数字,分别进行4次查表操作,然后将结果相加。

int count3(int n)
{
    int[] bitCount = new int[256]{0,1,1,2,1,2,...};
    return bitCount[n>>>24] +
           bitCount[(n&0x00ff0000) >> 16] +
           bitCount[(n&0x0000ff00) >> 8]  +
           bitCount[(n&0x000000ff)];
}

时间复杂度为O(1),但空间占用比较大,且数组的寻址开销也很大。只有在特定环境中才建议使用。

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
如果您想在 Unity 中查找某个 GameObject 的重孙(grandchild),您可以使用 Transform.Find() 方法来查找。例如,如果您想查找名为 "Grandchild" 的重孙 GameObject,您可以按照以下方式编写代码: ```csharp // 查找名为 "Grandchild" 的重孙 GameObject Transform grandchild = transform.Find("Child1/Child2/Grandchild"); // 检查是否成功找到了 GameObject if (grandchild != null) { // 找到了,可以对其进行操作 grandchild.gameObject.SetActive(false); } else { // 没有找到 Debug.Log("Could not find grandchild GameObject."); } ``` 在这个例子中,我们首先获取当前 GameObject 上的 Transform 组件(这里使用了 transform 变量),然后使用 Find() 方法来查找子 GameObject "Child1",再查找其子 GameObject "Child2",最后找到其重孙 GameObject "Grandchild"。注意,查找的路径是从当前 GameObject 的 Transform 组件开始的,所以我们不需要在路径中包含当前 GameObject 的名称。 如果您想查找多个重孙 GameObject,可以使用 Transform.FindChild() 方法,该方法返回一个 Transform[] 数组,其中包含所有匹配的子孙 GameObject。例如: ```csharp // 查找名为 "Grandchild" 的所有重孙 GameObject Transform[] grandchildren = transform.FindChild("Child1/Child2/Grandchild"); // 检查是否成功找到了 GameObject if (grandchildren.Length > 0) { // 找到了,可以对其进行操作 foreach (Transform grandchild in grandchildren) { grandchild.gameObject.SetActive(false); } } else { // 没有找到 Debug.Log("Could not find any grandchild GameObjects."); } ``` 在这个例子中,我们使用了 FindChild() 方法来查找所有名为 "Grandchild" 的重孙 GameObject,返回一个 Transform[] 数组。如果找到了任何匹配的 GameObject,我们可以使用 foreach 循环遍历数组,并对每个 GameObject 进行操作。如果没有找到任何匹配的 GameObject,我们会输出一条提示信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值