codewars——codewars——Bit Counting

Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case

思路

啧啧,如果是python代码这道题毫无难度,如果用C++的话,我确实也不知道C++有哪些轮子,估计得自己造轮子了。

十进制转二进制

原理就是一直对余数取对2的模,直到商为0,然后把余数倒序即可。我自己造轮子吧,希望时间上不会太久。

#include <vector>
#include <iostream>
using namespace std;
unsigned int countBits(unsigned long long n);
int main()
{
    cout << countBits(0) << endl;
    return 0;
}
unsigned int countBits(unsigned long long n)
{
    if (n == 0)
        return 0;
    unsigned int count = 0;
    cout << "start n:" << n << endl;
    vector<unsigned int> T;
    do
    {
        T.push_back(n % 2);
        n /= 2;
    } while (n / 2 != 0);
    T.push_back(1);
    for (auto p = T.begin(); p != T.end(); ++p)
    {
        if (*p == 1)
        {
            count++;
        }
    }
    return count;
}

代码来咯,首个用C++写的codewars,对我来说是个里程碑。
但是……不得不说python真的简单,来看一下python代码

def count(n):
    return str(bin(n)).count('1')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值