zoukankan      html  css  js  c++  java
  • 二进制中1的个数

    题目描述

    输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
     
    对于这道题我们很容易想到的是先判断二进制数最右边的第一位是不是1,。接着把输入的整数右移一位,这样每次移动一位,直到整个整数变为0。
    但是需要注意的是,如果输入一个负数,例如:0x80000000。把负数0x80000000右移一位的时候,不是简单的把最高位1移到第二位变成0x40000000,而是0xC0000000.如果一直做右移运算,最终这个数字会变成0xFFFFFFF而陷入死循环。所以,采用左移的方式。
    #include <iostream>
    #include <algorithm>
    #include "string.h"
    #include "stdio.h"
    #include <vector>
    #include <deque>
    #include <stack>
    #include <map>
    #include <utility>
    #include "math.h"
    using namespace std;
    
    class Solution {
    public:
         int  NumberOf1(int n) {
             int count = 0;
             unsigned int flag = 1;
             while(flag)
             {
                 if(flag&n)
                     count++;
                 flag = flag<<1;//每次像左移动一位,测试第二位...一直到最高位是否为1
             }
             return count;
         }
    };
    
    int main()
    {
        int n = 5;
        Solution solution;
        int count = solution.NumberOf1(n);
        cout<<count<<endl;
    }
  • 相关阅读:
    「WC2021」表达式求值
    [补]「WC2021」括号路径
    「CEOI2020」星际迷航
    「CEOI2018」斐波那契表示法
    CF913F
    CF1017G The Tree
    NOI2020 超现实树
    LOJ 6714 Stupid Product
    LOJ 575. 不等关系
    CF1267G
  • 原文地址:https://www.cnblogs.com/omelet/p/6652221.html
Copyright © 2011-2022 走看看