After learning the process control today, I felt that I could answer the first question of the test question. So I opened eclipse with excitement. Not much nonsense .. Check the code.
Package com. itheima;
/**
* Question 1: What method is more efficient for programming to calculate a value equal to 3 by 8?
* @ Author Liqing
*
* Idea: because the computer processes data in binary format, 8 equals to the Power 3 of 2.
* Therefore, you can use the left shift operator in the shift operator to calculate this question more efficiently.
*/
Public class test1
{
Public static void main (string [] ARGs)
{
System. Out. println (3 <3 );
}
}
Then we found that this method has limitations, not the Npower of 2. Then I wrote a judgment. The Code is as follows:
/* Because this method has some limitations, You must judge the multiplier,
* If the number is an N-power integer of 2, the Left shift operation is used. If not, use normal operations.
*/
Public class test1
{
/* Because the binary value of the N-power integer with a base number of 2 is only 1, and the others are 0.
* If & the last single-digit number with the highest bit of 0 and the remaining number with the same number of digits is 1, the result is 0. For example:
* 1000 & 0111 = 0,100 & 01 = & 001 = 0 ......
* This number is the integer to the Npower of the base number 2 minus 1.
* Determine whether 2 is the nth power of the base number, and then take the value of N.
* Because 2 (10) = 2 to the power of 1, 4 (100) = 2 to the power of 2, 8 (1000) = 2 to the power of 3 ......
* As long as we subtract 1 from the binary number of this number, this is what we want.
* You can use & 1 to determine whether the value of the binary number is 1. If the value is not 1, move one digit to the right for determination.
*/
Public static void main (string [] ARGs)
{
Int x = 3;
Int y = 2;
Int z = 0; // used to record the number of shift operations. If the initial value is set to 0, you do not need to subtract one.
// The Npower integer with the base number 2 must be greater than 1. Add y> 0 to prevent incorrect data input.
If (Y> 0) & (Y-1) = 0) // when y meets y> 0 and Y & (Y-1) when it is set to 0, this number is an integer that uses 2 as the base number to the Npower.
{
While (Y & 1) = 0)
{
Y> = 1;
Z ++;
}
System. Out. println ("this is the result of the shift operation:" + (x <z ));
}
Else
{
System. Out. println ("this is the result of a normal operation:" + (x * y ));
}
}
}