11. The number of 1 in binary
Enter an integer that outputs the number of 1 in the binary representation. Where negative numbers are expressed in complement.
(1) Optimal solution
1 Public classSolution {2 Public intNUMBEROF1 (intN) {3 intCount=0;4 while(n!=0){5n = n& (n-1);6count++;7 }8 returncount;9 }Ten}
(2)
1 Public classSolution {2 Public intNUMBEROF1 (intN) {3 intCount=0;4 intFlag=1;5 while(flag!=0){6 if((N&flag)!=0){7count++;8 }9Flag = flag<<1;Ten } One returncount; A } -}
(3) Note that:>>> is the right shift of 0 of the logical right shift,>> is the right to move the symbol bit of the arithmetic right shift
1 Public classSolution {2 Public intNUMBEROF1 (intN) {3 intCount = 0;4 while(n!=0){5 if((n&1) ==1){6count++;7 }8n = n>>>1;9 }Ten returncount; One } A}
12, the value of the whole number of square
The integer exponent of the floating-point base and int type given a double type. The exponent of the base of the second party. (1)
1 Public classSolution {2 Public DoublePower (DoubleBaseintexponent) {3 if(exponent==0)return1;4 if(exponent<0){5 return1/base* (Power (Base, exponent+1));6}Else{7 returnBase* (Power (Base, exponent-1));8 }9 }Ten}
Java implementation of "sword Point offer" (ii) 11~20 update