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 题目总结

  • 相关阅读:
    LGWR Trace Warning: Log Write Time ? Maybe not an issue
    Transaction & Undo
    XML Function at a glance
    Java step by step (1) : simple Spring IoC container
    First Impression on BBED: recover deleted rows
    【SQL*PLUS】Copy Command
    SYS_CONTEXT('USERENV', 'HOST') Return NULL & Oracle Fixed Tables
    ORA12519
    Some ORAs (32001, 00106)
    First Impression on BBED: explore block structure using map command
  • 原文地址:https://www.cnblogs.com/cnoodle/p/11681978.html
Copyright © 2011-2022 走看看