Offer surface prove safety questions 15 (java version): the number of 1s in binary

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/littlehaes/article/details/91411179

welcome to my blog

Offer surface prove safety questions 15 (java version): the number of 1s in binary

Title Description

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

Thinking

  • Low priority logical operation, attention bracketed
  • N Do not let the right, because if n is negative, then the right of the course will be supplemented by the highest level 1, leading to erroneous results or even an infinite loop
  • Should be allowed to flag to the left, when the flag is 1 at the highest bit, then left again, flag will become 0
  • Note int type flag in the left-flag when moved to the highest level is a negative number, so the conditional use! = 0 instead of> 0

the complexity

  • Time complexity: O (1), a shift is required 32 times
  • Space complexity: O (1)
public class Solution {
    public int NumberOf1(int n) {
        int count=0;
        int flag=1;
        while(flag != 0){ // 1不断向左移位 
            if((n & flag) != 0) // 要注意:逻辑与的优先级非常低
                count++;
            flag = flag << 1;    // 最需要注意的是:int类型的1移位到最高位时表示的是负数, 所以条件判断中要用!=0, 而不是>0
        }
        return count;
    }
}

Better way: There are several relatively few 1

  • Core: n & (n-1) This operation will rightmost n 1 becomes 0
public class Solution {
    public int NumberOf1(int n) {
        int count=0;
        while( n != 0){
            count++;
            n = n & (n-1);
        }
        return count;
    }
}

Guess you like

Origin blog.csdn.net/littlehaes/article/details/91411179