Topic:
Implement a function, enter an integer, and output the number of 1 in the binary representation of the integer. For example, to represent 9 as binary is 1001, 2 bits is 1, the function outputs 2
Solution: The integer minus one and the original number of the operation, will be the integer binary representation of the lowest bit 1 into 0, and how many times the operation will have the number of 1.
1 Packagesolution;2 /**3 * The sword refers to the offer surface question 10: The number of 1 in the binary4 * Title: Please implement a function, enter an integer, output the integer binary representation of the number of 1. 5 * For example, 9 is represented as binary is 1001, 2 bits is 1, the function outputs 26 * Solution: The integer minus one and the original number to do and operation, will be the integer binary representation of the lowest bit of 1 into 0, and the operation of how many times the number of 17 * @authorGL8 *9 */Ten Public classno10bitoperation { One A Public Static voidMain (string[] args) { - intnumber1=11; -System.out.println ("The number of 1 in the binary of integer 11 is:" +Numberofone (Number1)); the //int type integers in Java consist of 4-byte 32-bit - intNumber2=-11; -System.out.println ("The number of 1 in the binary of integer 11 is:" +Numberofone (number2)); - + - } + Public Static intNumberofone (intNumber ) { A intCount=0; at - while(number!=0){ -count++; -number=number& (number-1); - } - returncount; in } - to}
Sword Point offer Java implementation--the number of 1 in the question 102 binary