js- offer brush prove safety record title (bit operation)

1. The number of binary 1

My solution

The idea is to start right number is converted to binary representation, with toString () method, and then indexOf to find a record. Then run on vscode, I think rather beautiful, not complement it!

Other analysis

Here involves some basic computer knowledge, this science had forgot, here to record tidy.
The first is the most basic anti-code complement the original code, the following links written very clearly: the original code, anti-code complement Detailed

  • It is stored in the computer complement
  • Each integer is 4 bytes, 32-bit
  • A positive number of the original code, anti-code and complement all the same

Method a: bitwise Analyzing

  • The operational definition set binary number n, then:
    when n & 1 = 0, then n binary rightmost one is 0;
    if n & 1 = 1, then n binary rightmost one is 1.

  • According to the above description, the following cycle:
    when the number n is not a move to left and right is equal to 0, the end of the cycle;
    n&1 == 1, , count++n the right one.

Question: how do the number n is negative

  • Complement the most significant bit is 1 is represented as a negative sign bit.
  • n>>1, Signed right, to the left to fill a position, the endless loop;
  • n>>>1, Unsigned shift right, 0 to the left to fill the last number n becomes 0.
function NumberOf1(n){
    let count = 0
    let flag = 1
    while(n){
        count +=n&flag
        n = n >>>1
    }
    return count
}

Method two: n & (n-1)
This method is ingenious

  • n-1: n binary digits rightmost 1 becomes 0, the 01 on the right have become 1
  • n & (n-1): n rightmost binary digit 0 becomes 1, the other bits unchanged
  • 1 n number of how many, how many of these operations will be able to do, know the number n becomes 0Here Insert Picture Description
function NumberOf1(n){
    let count = 0
    while(n){
        n&=n-1
        count++
    }
    return count
}
Published 21 original articles · won praise 0 · Views 178

Guess you like

Origin blog.csdn.net/adrenalineiszzz/article/details/104837967