输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
下面这种方法只适用于正数,负数不适用,右移一位,对于负数来讲,左边补的是1。
class Solution { public: int NumberOf1(int n) { int count = 0; while(n != 0) { if((n & 1) == 1) count++; n >>= 1; } return count; } };
View Code
class Solution { public: int NumberOf1(int n) { int count = 0; unsigned int num = n; while (num != 0) { if ((num & 1) == 1){ count++; } num = num >> 1; } return count; } };
View Code
负数右移动,左边补1。所以将负数转成正数,这样再计算1的个数即可。
使用下面这种方法
class Solution { public: int NumberOf1(int n) { int count = 0; while (n != 0) { ++count; n = (n - 1) & n; } return count; } };
View Code
原文链接: https://www.cnblogs.com/yuguangyuan/p/5884013.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;
也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/398130
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!