为什么我的计数领先零“程序故障? [英] Why is my 'count leading zero' program malfunctioning?

查看:111
本文介绍了为什么我的计数领先零“程序故障?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是返回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, return 3 yes?



8 // 1000

解决方案

在无符号整数中为零的前导比特的数量,并且其假定为32比特的整数。



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


Here is code which returns number of leading zeros from Hacker's Delight book:

#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;
}

and when I enter number 8 it return 8 and is it correct maybe it should return 3 yes?

8//1000

解决方案

It returns the number of leading bits that is zero in an unsigned integer , and it assumes an integer is 32 bits.

8 is 0000 0000 0000 0000 0000 0000 0000 1000 binary, and it should return 28 for that, as there's 28 leading bits zero before the first 1 bit. If you're running this on something where an integer is not 32 bits, it won't work.

这篇关于为什么我的计数领先零“程序故障?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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