码迷,mamicode.com
首页 > 其他好文 > 详细

二进制中1的个数

时间:2019-02-24 10:36:22      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:public   一个   res   turn   题目   while   bit   位运算   二进制   

二进制中1的个数

题目描述

输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

C++中位运算符: 与&, 或|, 异或^, 左移<<, 右移>>

其中左移操作最右边补0, 右移操作最左边补与符号为相同的0或1

0101 << 2 = 0100

1101 >> 2 = 1111

0101 >> 2 = 0001

版本一: 由于正负关系, 不能右移操作数, 所以要左移标志为来进行与运算

class Solution {
public:
     int  NumberOf1(int n) {
         int res = 0;
         int bit = 1;
         
         while (0 != bit) {
             if (n & bit) {
                 res++;
             }
             bit = bit << 1;
         }
         
         return res;
     }
}; 

版本二: 详解见《剑指offer》P102

class Solution {
public:
     int  NumberOf1(int n) {
         int res = 0;
         
         while (n) {
             res++;
             n = (n - 1) & n;
         }
         
         return res;
     }
};

二进制中1的个数

标签:public   一个   res   turn   题目   while   bit   位运算   二进制   

原文地址:https://www.cnblogs.com/hesper/p/10425406.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!