剑指offer 面试题15 二进制中1的个数

mac2025-12-09  1

题目描述: 输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

可能首先会想到,每次把这个数进行除以2,或者进行右移操作,但是考虑到负数的情况,并不适用

可以借助一个flag, 保持n不动,而每次左移flag(这个flag是unsigned类型)

#include <iostream> #include <string> #include <memory> #include <vector> #include<cmath> #include<algorithm> using namespace std; class Solution { public: int NumberOf1(int n) { int count=0; unsigned int flag=1; while(flag!=0) { if((n&flag)!=0) { count++; } flag=flag<<1; } return count; } };

另有一种更简洁,更快速的办法,n&(n-1)每次将n最右边的1变为0,复杂度与n中1的个数有关:

class Solution { public: int NumberOf1(int n) { int count=0; while(n) { n=n&(n-1); count++; } return count; } };
最新回复(0)