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

    题目描述

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

    解题思路

    1. 利用1移位,与数的每一位比较,当与的结果不为0,则说明当前位为1,count加1,否则为0,直到1移位后为0,最后返回count。

    2. 如果n的二进制位为1010100,那么n-1的二进制位为1010011,那么这两个数相与得到1010000,即将n最后一位1变成0,那么每次n不为0,则count加1,n变为n&(n-1),知道n为0,返回count。

    实现

    1. 方法1
    public class Solution {
         public int  NumberOf1(int n) {
              int t = 1;
              int count = 0;
              while (t != 0){
                  if ((n & t) != 0) count++;
                  t <<= 1;
              }
              return  count;
         }
    }
    
    1. 方法2
    public class Solution {
         public int  NumberOf1(int n) {
              int count = 0;
              while (n != 0){
                   count ++;
                   n &= (n-1);
              }
              return count;
         }
    }
    
  • 相关阅读:
    python中元类(metaclass)的理解
    aiohttp
    async/await
    asyncio
    协程
    Bayesian Non-Exhaustive Classification A case study:online name disambiguation using temporal record streams
    技术网址
    网站
    各种网址
    OpenGL学习网址2
  • 原文地址:https://www.cnblogs.com/ggmfengyangdi/p/5767244.html
Copyright © 2011-2022 走看看