11209: 【原1209】数数
题目
题目描述
author: Qinglin Li 原OJ链接:https://acm.sjtu.edu.cn/OnlineJudge-old/problem/1209
Description
Little Jealous Joker是个比较“2”的人,特别喜欢2进制。有一天,Little Jealous从书中翻出来N个数a(1),a(2),...,a(n),他希望把这些数全部转化为2进制,数一数里面一共有多少个1。由于Little Jealous Joker已经“2”到不会数数了,请你帮帮他吧。
Input Format
第一行一个数N 第二行N个数a(1), a(2), ..., a(n),以空格隔开
Output Format
一个数,1的总个数
Sample Input
3
3 4 5
Sample Output
5
Limits
n<=100,000 a(i)不超过32位带符号整数(int)的范围
FineArtz's solution
/* 数数 */
#include <iostream>
using namespace std;
int main(){
int n, ans = 0;
cin >> n;
for (int i = 1; i <= n; ++i){
int a = 0;
cin >> a;
while (a > 0){
if (a % 2) ++ans;
a /= 2;
}
}
cout << ans << endl;
return 0;
}
ligongzzz's solution
#include "iostream"
#include "cstdio"
using namespace std;
int main() {
int num;
cin >> num;
long long ans = 0;
for (int i = 0; i < num; ++i) {
int temp;
scanf("%d", &temp);
//转二进制
for (; temp > 0; temp = temp >> 1)
if (temp % 2 == 1)
++ans;
}
cout << ans;
return 0;
}
q4x3's solution
#include <iostream>
#define POW(c) (1 << (c))
#define MASK(c) (((unsigned long) -1) / (POW(POW(c)) + 1))
#define ROUND(n, c) (((n) & MASK(c)) + ((n) >> POW(c) & MASK(c)))
using namespace std;
int main()
{
int n, ans = 0;
cin >> n;
for (int i = 1;i <= n;++ i) {
int num;
cin >> num;
num = ROUND (num, 0);
num = ROUND(num, 1);
num = ROUND(num, 2);
num = ROUND(num, 3);
num = ROUND(num, 4);
ans += num; // O(loglognum)
/*while (0 < num) {
++ ans;
num &= num - 1;
}*/ // O(ones)
/*while (0 < num) {
ans += (1 & num);
num >>= 1;
}*/ // O(lognum)
}
cout << ans << endl;
}
skyzh's solution
#include <iostream>
using namespace std;
int main() {
int n;
long long total = 0;
cin >> n;
for (int i = 0; i < n; i++) {
unsigned int f;
cin >> f;
while (f > 0) {
total += f & 1;
f >>= 1;
}
}
cout << total << endl;
return 0;
}
victrid's solution
#include <iostream>
using namespace std;
int main()
{
int N;
cin >> N;
int num;
int cnt = 0;
for (int i = 0; i < N; i++)
{
cin >> num;
while (num != 0)
{
if (num & 1)
cnt++;
num = num >> 1;
}
}
cout << cnt;
return 0;
}
yyong119's solution
#include <iostream>
using namespace std;
int main() {
ios::sync_with_stdio(false);
int n, total = 0;
cin >> n;
while (n--) {
long tmp;
cin >> tmp;
if (tmp < 0) tmp = -tmp;
while (tmp) {
total += tmp % 2;
tmp /= 2;
}
}
cout << total << endl;
return 0;
}