1. 程式人生 > 其它 >二進位制中1的個數--與運算

二進位制中1的個數--與運算

題目描述

在這裡插入圖片描述

程式碼

public class Solution {
    // you need to treat n as an unsigned value

    /*
        & 與運算:0&0=0   1&0=0   0&1=0   1&1=1
		| 或運算:有1則1
		^ 異或:   同則0,不同則1
    */
    public int hammingWeight(int n) {
       
        int res = 0;
        while(n != 0){
            res = res + (n &
1); //最右一位 n = n >>> 1; //無符號右移一位,,Java 中無符號右移為 ">>>" } return res; } }