求int型正整數(shù)在內(nèi)存中存儲(chǔ)時(shí)1的個(gè)數(shù) 輸入一個(gè)int型的正整數(shù),計(jì)算出該int型數(shù)據(jù)在內(nèi)存中存儲(chǔ)時(shí)1的個(gè)數(shù)。
輸入描述: 輸入一個(gè)整數(shù)(int類型)
輸出描述: 這個(gè)數(shù)轉(zhuǎn)換成2進(jìn)制后,輸出1的個(gè)數(shù)
輸入例子: 5
輸出例子: 2
解答:#include <iostream>#include <vector>using namespace std;int main(){ int n; vector<int>v; while(cin>>n) { int count = 0; v.clear(); while(n) { v.push_back(n%2); n/=2; } for(vector<int>::iterator it=v.begin();it!=v.end();++it) { if(*it) count++; } cout<<count<<endl; } return 0;}解法二其實(shí)這道題的原意是想讓編程人員使用位運(yùn)算,代碼如下:#include <iostream>using namespace std;int main(){ int n; while(cin>>n) { int count = 0; while(n) { n = n&(n-1); count++; } cout<<count<<endl; } return 0;}新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注