Beauty of programming _ 006 calculate the number of 1 in the binary number

Source: Internet
Author: User
// Calculate the number of 1 in the binary number. Public class test_006 {public static void main (string [] ARGs) {int number = 123; int Total = 0; // number of records 1 system. out. println ("number:" + number); system. out. println ("digit binary format:" + integer. tobinarystring (number); system. out. println ("------------------"); // solution 1: Calculate the remainder of each time and 2 to see if it is an odd number. If yes, add one, the final result is the number of 1 in the binary representation. While (number> 0) {If (Number % 2 = 1) {total ++;} number/= 2;} system. out. println ("Number of 1 in solution 1:" + total); system. out. println ("------------------"); // solution 2: A loop is also used, which is simplified by the displacement operation. Number = 123; Total = 0; while (number> 0) {total + = Number & 1; number >>=1;} system. out. println ("Number of 1 in solution 2:" + total); system. out. println ("------------------"); // solution 3: Use a clever operation. Each time V & (V-1) deletes the last digit 1 in the binary representation, this technique can reduce the number of cycles. Number = 123; Total = 0; while (number> 0) {number & = (number-1); Total ++;} system. out. println ("Number of numbers 1 in solution 3:" + total); system. out. println ("------------------"); // solution 4: look-up table method. Because only 8 bits of data are available, directly create a table that contains the number of 1 in each number, and then look up the table. Complexity O (1 ). // Directly record all results in an array, and then query as needed ,}}

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.