gpt4 book ai didi

c++ - 为什么我的 'count leading zero' 程序出现故障?

转载 作者:行者123 更新时间:2023-11-28 03:56:49 25 4
gpt4 key购买 nike

这是从 Hacker's Delight 书中返回前导零数的代码:

#include <iostream>
using namespace std;

int nlz(unsigned x) {
int n;
if (x == 0) return(32);
n = 1;
if ((x >> 16) == 0) {n = n +16; x = x <<16;}

if ((x >> 24) == 0) {n = n + 8; x = x << 8;}
if ((x >> 28) == 0) {n = n + 4; x = x << 4;}
if ((x >> 30) == 0) {n = n + 2; x = x << 2;}
n = n - (x >> 31);
return n;
}

int main(){
int x;
cin>>x;
cout<<nlz(x)<<endl;

return 0;
}

当我输入数字 8 时,它返回 8,它是否正确,也许它应该返回 3 是吗?

8//1000

最佳答案

它返回无符号整数中前导位数为零的位数,并假定整数为 32 位。

8 是 0000 0000 0000 0000 0000 0000 0000 1000 二进制,它应该返回 28,因为在第一个 1 位之前有 28 个前导位为零。如果您在整数不是 32 位的东西上运行它,它将无法工作。

关于c++ - 为什么我的 'count leading zero' 程序出现故障?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3232534/

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