2015 Huawei Machine Test--Calculate the number of 0 of binary number

Source: Internet
Author: User

Description:
Enter a 10 decimal number, calculate the number corresponding to 0 in the binary, and note that all 0 before the first 1 of the left does not need to be calculated. There is no need to consider the case of negative numbers.

Topic Category: Bit arithmetic
Difficulty: Beginner
Run time limit: Unlimited
Memory Limit: Unlimited
Stage: Pre-employment practice
Input:
The decimal non-negative number to calculate

Output:
The number of 0 after the first 1 in the binary

Sample input:
2

Sample output:

1


Problem Solving Ideas:

For a given number of N, a bitwise operation of:n=n& (n-1) can be used to calculate the number of 1 in the corresponding binary, which is count1. The input=n,input=input>>1 one by one to get the number of input 1, for Count2, if input&1==1, then the corresponding bit is 0, the Count T plus 1 operation, when count1= Count2, the loop terminates, at this point can get t, that is, 0 number, concrete implementation see the code below.

The code is as follows:

public class Number_ofzero_bits{public static void Main (string[] args) {Scanner sc=new Scanner (system.in); Sc.hasnext ()) {int input=sc.nextint (); if (input<0) {return;} int Count1=0,count=0,t=0;int n=input;while (n!=0) {n=n& (n-1); count++;} while (input!=0) {if ((input&1) ==1) {count1++;if (count1==count) {break;}} else{t++;} input=input>>1;} System.out.println (t);} Sc.close ();}}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

2015 Huawei Machine Test--Calculate the number of 0 of binary number

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.