The Java implementation asks for the number of 1 in the binary number of an integer __java

Source: Internet
Author: User

This question is still written in the time encountered, did not think too much, direct use of the most direct shift addition method, although the results can be obtained, but the program efficiency is low.

Later discovered that using n=n& (n-1) method, the efficiency will be higher, the first code.

<span style= "FONT-SIZE:18PX;" >public static void Main (string[] args) {
	//TODO auto-generated method stub
	Scanner Scanner = new Scanner (Syst em.in);
	int n = scanner.nextint ();
	int count = 0;  
        while (n!= 0)
        {  
            count++;  
            n=n& (n-1);  
         }  
		System.out.println (count);
	}
	</span>

Analysis: The while loop only needs to execute 1 of the number of n + 1 times. Take n=19 as an example, the binary number is: 0001 0011

First cycle: 0001 0011 & 0001 0010 = 0001 0010

Second cycle: 0001 0010 & 0001 0001 = 0001 0001

Cycle number three: 0001 0001 & 0001 0000 = 0001 0000

Fourth cycle: 0001 0000 & 0000 1111 = 0000 0000, at this time n=0, jump out of the loop.

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.