输出一个整数的二进制中“1”的个数(c++每日一题)

分手后的思念是犯贱 2023-02-18 14:02 90阅读 0赞

输入一个整数

输出一的个数

示例:

输入 5

输出 2

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2FtYmlndW91c19f_size_16_color_FFFFFF_t_70

  1. #include<iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. int n;
  6. while (cin >> n)
  7. {
  8. int o;
  9. int count = 0;
  10. while (n)
  11. {
  12. o = n & 1;
  13. if ( o== 1)
  14. {
  15. count++;
  16. }
  17. n=n >> 1;
  18. }
  19. cout << count << endl;
  20. }
  21. }

发表评论

表情:
评论列表 (有 0 条评论,90人围观)

还没有评论,来说两句吧...

相关阅读