gpt4 book ai didi

c - 如何在不使用逻辑非或控制结构的情况下确定整数是否为零

转载 作者:行者123 更新时间:2023-11-30 21:47:12 26 4
gpt4 key购买 nike

如何使用位运算(~ ^ & | >> <<)、逻辑运算(&& || 但不能使用!)、算术运算(+ - */)来完成此功能(C 语言) 。

int isZero(int a){
//if a == 0, return 1, if a != 0, return 0
}


或者

bool isZero(int a){
// if a == 0, return true, if a != 0, return false
}


不能使用if、for、while语句,不能使用==、!=等操作。


评论:有人给出解决方案:

boolean isZero(int a) {return a;}

但是,技巧是如果 a 等于 0,我们需要返回 1(或 true),并且我们不能使用 !操作。

最佳答案

这样就没有“禁止的”运算符了。

int isZero(unsigned int n)
{
return (((n | (~n + 1)) >> 31) & 1) ^ 1;
}

关于c - 如何在不使用逻辑非或控制结构的情况下确定整数是否为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23846371/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com