uva12893 Count It

uva12893

uDebug12893

题目给了段代码,然后要求计算当n大于10的6次方,跑这段代码出来的结果。n的二进制表示中有多少个1,还是老老实实地数吧。。。

python版本AC代码

def count_1(x):
	ans = 0
	while x > 1:
		ans += x % 2
		x //= 2
	if x == 1:
		ans += 1
	return ans

testcase = int(input())
while testcase > 0:
	testcase -= 1
	n = int(input())
	print(count_1(n))

C++版本AC代码

#include <iostream>
#include<cstdio>
using namespace std;

//#define ZANGFONG

int solve(long long x)
{
    int ans = 0;
    while(x > 1)
    {
        ans += x % 2;
        x /= 2;
    }
    if(x == 1) ans += 1;
    return ans;
}

int main()
{
    #ifdef ZANGFONG
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
    #endif // ZANGFONG
    int testcase;
    long long n;
    scanf("%d\n",&testcase);
    while(testcase--)
    {
        scanf("%lld\n",&n);
        printf("%d\n",solve(n));

    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zangfong/article/details/84564188