您的位置:首页 > 职场人生

面试题之编程之美 求一个整数中二进制数1的个数

2014-01-09 08:00 225 查看

求一个整数中二进制数1的个数

真言

Study hard and you will get what you want.

引言

Everyone has his or her problems, just solve them.

题目(此题目和编程之美的题目还是不一样的)



思路

思路一(画图举例子)



时间复杂度 O(整数转换为二进制后 1 的个数)

思路二(画图举例子)



时间复杂度O(整数转换二进制后 二进制数的位数)

实验

对每一个算法测试从1到100,000,000  时间耗费比较

思路一



思路二



代码

sulution1.cpp

#include<iostream>
#include<Windows.h>
#include<ctime>
using namespace std ;

// define size for data
const int size = 100000000;

// function declare to the problem
int bit_number(int x);

// main function
int main()
{
WORD s,e;
s = GetTickCount();
int * data = new int[size];
for(int i = 0;i<size;i++)
{
data[i] = bit_number( i );
}
e = GetTickCount();
cout<<"it costs "<<e-s<<" 毫秒"<<endl;
system("pause");
return 0;
}

// function define to the problem
int bit_number(int x)
{
if(x < 0)
{
cout<<"exception input of bit_number"<<endl;
}

int countx = 0;
while( x )
{
countx ++;
x = x & (x-1);
}
return countx;
}


 

solution2.cpp

#include<iostream>
#include<Windows.h>
#include<ctime>
using namespace std;

// define size for data
const int size = 100000000;

// function declare to the problem
int bit_number(int x);

// main function
int main()
{
WORD s,e;
s = GetTickCount();
int * data = new int[size];
for(int i = 0;i<size;i++)
{
data[i] = bit_number( i );
}
e = GetTickCount();
cout<<"it costs "<<e-s<<"毫秒"<<endl;
system("pause");
return 0;
}

// function define to the problem
int bit_number(int x)
{
int count = 0;
while(x)
{
// whether the end of x is true
if(x & 1)
count ++;

// righter and left get 0
x = x >> 1;
}
return count;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  面试题
相关文章推荐