What does this condition mean to complete a Java cycle?

I am wondering if anyone knows what the termination condition means in the assumption is that the following is assumed for the loop.

for (int i = 0; i < 1 << Level; i++) { ... } 
+5
source share
3 answers

<< shifts the bit of the first operand n times to the left, where n is the second operand.

Therefore, 1 << Level shifts a single bit 1 number 1 Level times to the left, which is equivalent to calculating the level 2 ^.

So i < 1 << Level equivalent to i < Math.pow(2,Level) .

+8
source

Simply put

 for (int i = 0; i < 1 << Level; i++) { ... } 

equally

 for (int i = 0; i < Math.pow(2,Level); i++) { ... } 

Thus, the for loop will work for "Math.pow (2, Level)" times, since you are calculating from 0 to Math.pow (2, Level) -1.

if Level = 2, then the cycle

 for(int i =0;i<4;i++){} 

if Level = 3, then the cycle

 for(int i =0;i<8;i++){} 

if Level = 5, then the cycle

 for(int i =0;i<32;i++){} 
+3
source

In addition to other answers, this can help put brackets around the expression if this is unclear

 for (int i = 0; i < (1 << Level); i++) { ... } 

In addition, since Level is a variable, it is suggested to have the lowercase letter ie Level , if it is not a constant, then it should be Level . And I think that overall it's readability> performance (if that's even a problem?). Thus, Math.pow(2,Level) much easier to understand, if you are not a low level programmer, it looks much bigger than Java than C.

0
source

Source: https://habr.com/ru/post/1235451/


All Articles