这里是返回前导零的数量从黑客的喜悦书代码:为什么我的“计数前置零”程序出现故障?
#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
它真的会返回8或28吗?如果8,你在使用什么样的机器? – nos 2010-07-12 21:50:53
我认为你会混淆前导零(28为8的32位表示)和尾随零(3为32位表示8)。 – 2010-07-12 21:53:36