描述
給定一個十進制非負整數N,求其對應2進制數中1的個數。
輸入
輸入包含一行,包含一個非負整數N。(N < 109)
輸出
輸出一行,包含一個整數,表示N的2進製表示中1的個數。
樣例輸入
100
樣例輸出
3
這道題比較簡單,如果一個數不能被2整除,那麼這個數二進制形式的最後一位就是1,可以通過這個來判斷1的個數。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <set>
#include <cmath>
#include <algorithm>
using namespace std;
int main()
{
int n,k=0;
cin>>n;
while(n>0)
{
if(n%2) k++; //判斷n二進制形式的最後一位有沒有1
n>>=1; //將n右移一位,等價於n/=2;
}
cout<<k; //輸出1的個數
return 0;
}
法二
除了這種方法,還可以用位運算來解決。
lowbit函數可以求出最後一位的1。例如:1100(二進制)用lowbit函數返回的是100(二進制),111用lowbit函數返回的是1。
寫法如下:
int lowbit(int x)
{
return x&(-x); //x和x的補碼進行與操作
}
用lowbit函數也可以很輕鬆的解除這個題。
代碼如下:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#define LL long long
using namespace std;
int lowbit(int x)
{
return x&(-x);
}
int main()
{
int n,k=0;
cin>>n;
while(n) {n-=lowbit(n); k++;}
cout<<k;
return 0;
}