题解 | 二进制数1

二进制数1

https://www.nowcoder.com/practice/bc4c7936f5ed42cbb9131b6f39aa272b

方法一:使用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;
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务