Number of binaries (JAVA)

Source: Internet
Author: User

Number of 1 in binary
  
Title Description Enter an integer that outputs the number of 1 in the binary representation.        Where negative numbers are expressed in complement. Idea: Use bitwise arithmetic to move 1 operations.      (First you have to know that the number in the computer is placed in 01来) 1, if by a number 11100, when its minus 1 is 11011, that is, minus 1 will be the number of the rightmost 1 to 0, and all subsequent numbers are reversed. 2, the two number and the 11000, the rightmost 1 becomes 0, and the other number is unchanged.      At this point 1 numbers plus 1.            3, repeat the operation until the number becomes 0, and get the number of all 1. The code is simple, as follows.
1      Public int NUMBEROF1 (int  n) {2         int count = 0; 3          while (n!=0) {4             count++; 5             n = n& (n-1); 6         }7         return  count; 8     }

Number of binaries (JAVA)

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.