The sword refers to the number of 1s in Offer-Java-binary

number of 1's in binary


Question:
Input an integer and output the number of 1s in the binary representation of the number. Negative numbers are represented in complement.
Code:

package com.hlq.test;

/**
 * @author helongqiang
 * @date 2020/5/13 21:56
 */

/**
 * 输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
 */

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 http://43.154.161.224:23101/article/api/json?id=324135983&siteId=291194637