• 二进制中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;
    }
  • 相关阅读:
    预防新型冠状病毒科普宣传网站
    四则运算
    结对审查
    最大子段和
    单元自动测试Junit
    浅谈过去,畅想未来
    第一次的结对编程
    代码审查
    单元测试
    junit4单元测试
  • 原文地址:https://www.cnblogs.com/omelet/p/6652221.html
Copyright © 2020-2023  润新知