二进制中1的个数(C 语言牛客网)

解题思路:

(1)因为左移会改变符号,因此这里考虑右移

(2)因为二进制无论是原码还是补码,当最后一位是0时,该整数必能整除2

(3)非负数,每次右移一位,补0,不改变1的个数,只有当被移位是1时才会改变

(4)负数(补码)每次右移一位,补1,增加1的个数,可以反其道而行之,我们计算出0的个数,再使用32减去该值

class Solution {
public:
     int  NumberOf1(int n) {
     	int count = 0;
         if (n>=0) {
         	while(n!=0) {
         		if (n%2!=0) count++;
         		n = n >> 1; 
			 }
			 return count;
		 } else {
		 	while(n!=-1) {
		 		if (n%2==0) count++;
		 		n = n >> 1;
			 }
			 return 32-count;
		 }
		 return count;
     }
};
发布了302 篇原创文章 · 获赞 277 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/coolsunxu/article/details/105587393