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