java data structures and algorithms (10) the number of 1s in binary

  • An integer that indicates the number of the output of the binary number 1 in. Wherein a negative number indicates a complement. Complete the following code:
public class Solution {
     public int NumberOf1(int n) {

    }
}
复制代码
  • Ideas:
    • Method 1: Use Integer.toBinaryString (n) Method
    • Method 2: an 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.
  • Solution1
public class Solution1 {
    public int NumberOf1(int n) {
        int count = 0 ;
        char[] array = Integer.toBinaryString(n).toCharArray();
        for(int i = 0 ; i <array.length;i++){
            if(array[i]=='1'){
                count++;
            }
        }
        return count;

    }
}
复制代码
  • Solution2
public class Solution2 {
   public int NumberOf1(int n) {
        int count = 0 ;
        while (0!=n){
            count++;
            n=n&(n-1);
        }
        return count;
    }
}
复制代码

Reproduced in: https: //juejin.im/post/5cf614caf265da1bbc6fc1a7

Guess you like

Origin blog.csdn.net/weixin_34273046/article/details/91415259