方法一:使用C语言的内建函数__builtin_popcountll

#include <iostream>

using i64 = long long;

int main() {
  std::ios::sync_with_stdio(false);
  std::cin.tie(nullptr);
  std::cout.tie(nullptr);

  i64 x;
  std::cin >> x;

  std::cout << __builtin_popcountll(x) << "\n";

  return 0;
}

方法二:模拟

#include <iostream>

using i64 = long long;

int main() {
  std::ios::sync_with_stdio(false);
  std::cin.tie(nullptr);
  std::cout.tie(nullptr);

  i64 x;
  std::cin >> x;

  int ans = 0;
  while(x){
    if(x & 1){
      ans++;
    }
    x >>= 1;
  }

  std::cout << ans << "\n";

  return 0;
}

方法三:(当前牛客编译器不支持)C++20后标准库<bit>中有std::popcount函数(它重载了C++中所有无符号整数的版本)

#include <iostream>
#include <bit>

using i64 = long long;

int main() {
  std::ios::sync_with_stdio(false);
  std::cin.tie(nullptr);
  std::cout.tie(nullptr);

  i64 x;
  std::cin >> x;

  std::cout << std::popcount(x) << "\n";

  return 0;
}

方法四:转成bitset,调用成员函数count

#include <iostream>
#include <bitset>

using i64 = long long;

int main() {
  std::ios::sync_with_stdio(false);
  std::cin.tie(nullptr);
  std::cout.tie(nullptr);

  i64 x;
  std::cin >> x;

  std::cout << std::bitset<64>(x).count() << "\n";

  return 0;
}