面试题之编程之美 求一个整数中二进制数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; }
相关文章推荐
- 读博客”求一个整数中二进制数1的个数“两种方法分析
- 面试题,求一个整数数组中和最大的连续子数组,例如:[1, 2, -4, 4, 10, -3, 4, -5, 1]的最大连续子数组是[4, 10, -3, 4](需写明思路,并编程实现)
- 面试题:编写一个将十进制数转换为任意进制的算法或函数
- 一个经典编程面试题的“隐退”
- 编程之美 给定一个整数N,那么N的阶乘N!末尾有多少个0?
- 【C语言】输入一个整数,输出该数二进制表示中1的个数(三种方法)
- 编写一个函数itob(int n,char s[], int b),将整数n转换为以b进制的数。保存到s中。
- 一个整数转换成2进制
- 如何计算一个整数转成2进制的1或者0 的个数
- 面试题:在一个数组中有0-99之间的整数101个(数组无序),用高效方法找出其中的唯一的重复元素!
- 面试题:求一个INT32整数里面有多少个位是置1 的
- 18. 微软面试题:输入一个表示整数的字符串,把该字符串转换成整数并输出
- 一个利用堆栈实现的正整数10进制向16进制的转化程序
- 几道经典的有关整数二进制的编程题(如:一个数二进制位的偶数位和奇数位交换)
- 1.输出一个整数的每一位。2. 编程实现: 两个int(32位)整数m和n的二进制表达中,有多少个位(bit)不同?
- 程序员面试题100题第22题——整数2进制表示中1的个数
- 基于Visual C++2013拆解世界五百强面试题--题2-输出和为一个给定整数的所有组合
- 基于Visual C++2013拆解世界五百强面试题--题2-输出和为一个给定整数的所有组合
- 编程珠玑_第十三章_生成一个随机整数的有序集合
- 谷歌面试题:输入是两个整数数组,他们任意两个数的和又可以组成一个数组,求这个和中前k个数怎么做?