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

69 篇文章 0 订阅
60 篇文章 3 订阅

求一个整数中二进制数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;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值