Sword Point offer Java implementation--the number of 1 in the question 102 binary

Source: Internet
Author: User


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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.