🔢
Algorithms & Data
Ctrlk
  • Overview
    • 1. Sort
    • 2. Data Structures
    • 3. How to construct Algorithm? Paradigm
  • Algorithm Problems
    • Problem Sources
    • AlgoExpert
    • Daily Algorithms
  • Top 75 LeetCode Questions to Save Your Time
    • Source
    • Problems
      • Interval
      • Heap
      • Array
      • Binary
        • 190. Reverse Bits
        • 268. Missing Number
        • x 338. Counting Bits
        • 12. 191. Number of 1 Bits
        • 11. 371. Sum of Two Integers
      • Graph
      • Tree
      • Dynamic Programming
      • String
      • Matrix
      • Linked List
  • Tip
    • Page 2
    • LinkedList
Powered by GitBook
On this page
  1. Top 75 LeetCode Questions to Save Your Time
  2. Problems
  3. Binary

12. 191. Number of 1 Bits

LogoNumber of 1 Bits - LeetCodeLeetCode

bitwise operators

JavaScript Bitwise Operators (with Examples)

with bitwise

without bitwise

Previousx 338. Counting BitsNext11. 371. Sum of Two Integers

Last updated 16 days ago

/**
 * @param {number} n - a positive integer
 * @return {number}
 */
var hammingWeight = function (n) {
    let cnt = 0;
    while (n ^ 0) {
        cnt = cnt + (n & 1);
        n = n >>> 1;
    }
    return cnt;
};

/**
 * @param {number} n - a positive integer
 * @return {number}
 */
const memo = {};
var hammingWeight = function(n) {
    if (memo[n] !== undefined) return memo[n];
    const bi = n.toString(2);
    let cnt = 0;
    for (let i = 0; i < bi.length; i++) {
        if (bi.charAt(i) === '1') cnt++;
    }
    memo[n] = cnt;
    return cnt
};