Prove safety offer: a binary number (the bit operation, leetcode191)

topic:

An integer that indicates the number of the output of the binary number 1 in. Wherein a negative number indicates a complement.

The source complement is a positive number

Complement negative number is positive negated complement -1

answer:

Solution one:

Honestly want to write about, write the result of a mess, but still ...... by the code is as follows:

public class Solution {
    public int NumberOf1(int n) {
        if(n==0){
            return 0;
        }
        //提前处理溢出
        if(n==-2147483648){
            return 1;
        }
        int count = 0;//1的数目
        boolean flag = true;
        if(n<0){
            flag = false;//负数
        }
        int target = Math.abs(n);
        while(target>0){
            if(target%2==1){
                count++;
            }
            target = target/2;
        }
        if(!flag){
            int last = n%2;
            count = (last==0)?(32-count):(32-count+1);
        }
        return count;
    }
}

Solution two:

Bit-wise comparison, as follows:

public class Solution {
    public int NumberOf1(int n) {
        int count = 0;
        int mask = 1;
        for(int i=0;i<32;i++){
            if((n&mask)!=0){
                count++;
            }
            n = n >> 1;
        }
        return count;
    }
}

 

Solution three:

This solution is really no way out ......

(Interpretation of handling the comments section chiefs)
If a non-zero integer, then this is an integer of at least 1. If we subtract the integer 1, then the original integer in the rightmost 1 will be changed to 0, the original becomes (0, then there's a 1 followed if the rightmost) 1 in all 01 will be back. All remaining bits will not be affected.
For example: a binary number 1100, from the third to the right of the number is in a rightmost 1. After subtracting 1, the third becomes 0, it later became two of 0 1 1 while the front remains unchanged, so the result is 1011. We found that the results of minus one is to a rightmost 1 bits are all starting to take backwards. This time the results after the original integer if we then do with the operation and subtract 1 from the original integer rightmost 1 the one who began all the bits will become 0. Such as the 1100 & 1011 = 1000. That put an integer minus 1, and then to do with the original integer arithmetic, the integer will rightmost 1 becomes 0. Then a binary integer of 1 how many, how much can be times such an operation.

code show as below:

public class Solution {
    public int NumberOf1(int n) {
        int count = 0;
        while(n!=0){
            count++;
            n = n&(n-1);
        }
        return count;
    }
}

leetcode Solution:

https://leetcode-cn.com/problems/number-of-1-bits/solution/wei-1de-ge-shu-by-leetcode/

Published 92 original articles · won praise 2 · Views 8420

Guess you like

Origin blog.csdn.net/wyplj2015/article/details/104843446