zoukankan      html  css  js  c++  java
  • [LeetCode] 191. Number of 1 Bits

    Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight).

    Example 1:

    Input: 00000000000000000000000000001011
    Output: 3
    Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
    

    Example 2:

    Input: 00000000000000000000000010000000
    Output: 1
    Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.
    

    Example 3:

    Input: 11111111111111111111111111111101
    Output: 31
    Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.

    Note:

    • Note that in some languages such as Java, there is no unsigned integer type. In this case, the input will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned.
    • In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3 above the input represents the signed integer -3.

    Follow up:

    If this function is called many times, how would you optimize it?

    题意是给一个二进制的数字,求出其中1的个数。这题需要用到一个位运算的特性,建议背下来,就是n & (n-1)会让n最右边的1变为0。所以只要记一个count,然后看看这个&的操作做几次,数字整个变为0,就说明过程中有几个1被变为0了。例子,

    代码如下,

    时间O(1) - 因为是位运算,再怎么样都只有32位

    空间O(1)

    JavaScript实现

     1 /**
     2  * @param {number} n - a positive integer
     3  * @return {number}
     4  */
     5 var hammingWeight = function(n) {
     6     let res = 0;
     7     while (n !== 0) {
     8         n &= n - 1;
     9         res++;
    10     }
    11     return res;
    12 };

    Java实现

     1 public class Solution {
     2     // you need to treat n as an unsigned value
     3     public int hammingWeight(int n) {
     4         int res = 0;
     5         while (n != 0) {
     6             n &= n - 1;
     7             res++;
     8         }
     9         return res;
    10     }
    11 }

    LeetCode 题目总结

  • 相关阅读:
    BE Learing 2 名词解释
    mysql学习笔记(二)之一个粗心的问题
    Struts2/XWork < 2.2.0远程执行任意代码漏洞分析及修补
    DataReceivedEventHandler 委托
    JS数组方法汇总 array数组元素的添加和删除
    jQuery学习总结(一)
    js的lock
    mysql学习笔记(一)之mysqlparameter
    Time Span Attack
    Web Vulnerability Scanner 7.0 Patch for 2010_09_21_01
  • 原文地址:https://www.cnblogs.com/cnoodle/p/11681978.html
Copyright © 2011-2022 走看看