剑指offer-面试题15-二进制中1的个数-位运算

/*
题目:
	二进制中1的个数,例如9为1001,有2位1.
*/
/*
思路:
	算法2:
		左移unsigned类型flag=1,和n做&运算,当flag移动中1的位置与n对应位置也为1时,则对应位置结果为1。
		算法一直执行32次。
	算法1:
		假设数字1101,1101-1=1100 ,1100&1101 = 1100,一次
		1100-1=1011,1011&1100=1000,二次
		1000-1=0111,0111&1000=0000,三次
		所以1101有3个1。
*/
/*
经验:
     把整数减去1和原整数做与运算,相当于把二进制中最右边的1变为0
*/ #include<iostream> #include<string.h> #include<algorithm> #include<math.h> using namespace std; int NumberOf1_solution1(int n){ int count = 0; while(n){ count++; n = (n-1) & n; } return count; } int NumberOf1_solution2(int n){ unsigned int flag = 1; int count = 0; while(flag){ if(flag & n ){ count++; } flag = flag << 1; } return count; } int main(){ cout<<NumberOf1_solution1(9)<<endl; cout<<NumberOf1_solution2(9)<<endl; }

   

猜你喜欢

转载自www.cnblogs.com/buaaZhhx/p/11845859.html