每天一道剑指offer-牛客网二进制中1的个数

  • 2019 年 10 月 4 日
  • 笔记

题目

每天一道剑指offer-牛客网二进制中1的个数 来源:牛客网对应专题

题目详述

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

题目详解

思路

就是剑指offer思路哈。

代码

public class Solution {      public int NumberOf1(int n) {          if(n == 0)              return 0;          int count = 0;          while((n&(n-1)) != 0)//这个就是每个整数减一然后与自身相与          {              count++;//如果不为0,那么说明还有1,              n = n & (n-1);          }          count++;//比如说循环开始的时候只有一个1,那么循环没进入循环体就结束了,所以这里需要count加一个1来计数          return count;      }  }