10. The number of binary 1
Algorithm Description
An integer that indicates the number of the output of the binary number 1 in. Wherein a negative number indicates a complement.
Problem-solving ideas
Solution 1: May cause an infinite loop of solution
N 1 and the number of input and computation done, left 1 bit are 0, and the operation result is 0 do; the result is 0 or 1 depends on the last one is 0 or 1
Enter n | 1 | 0 | 1 | 0 | 1 |
---|---|---|---|---|---|
1 | 0 | 0 | 0 | 0 | 1 |
result | 0 | 0 | 0 | 0 | 1 |
The main problem lies in the n >> 1
above negative is left up to the left 1
, resulting in an infinite loop
function NumberOf1(n)
{
// write code here
var count = 0;
while (n) {
if (n & 1)
count ++;
n = n >> 1;
}
return count;
}
Solution 2: General Solution
The 1
left one, and the n-done operation, 32-bit binary number 0 into the left 32
Enter n | 1 | 0 | 1 | 0 | 1 |
---|---|---|---|---|---|
1 | 0 | 0 | 1 | 0 | 0 |
result | 0 | 0 | 1 | 0 | 0 |
function NumberOf1(n)
{
// write code here
var count = 0;
var i = 1;
while (i) {
if (n & i)
count ++;
i = i << 1;
}
return count;
}
Solution 3: optimal solution
Discover the laws for binary numbers ①, ② after it by -1, then ① and ② do with the operation, the result of a less just 1
[Image dump the chain fails, the source station may have security chain mechanism, it is recommended to save the picture down uploaded directly (img-G2v8nsEG-1570784703829) (/ images / wins the offer / 10. .Png binary number 1)]
//.js
function NumberOf1(n)
{
// write code here
//不等于0
var count = 0;
while(n) {
count ++;
n = n & (n - 1);
}
return count;
}
//.java
public class Solution {
public int NumberOf1(int n) {
int count = 0;
while (n != 0) {
count++;
n = n & (n - 1);
}
return count;
}
}