I was looking into this video, for a really famous question for bit manipulation
He wrote this statement
count -= (1 << ((length - 1) / 2));
I am not able to understand.
Consider if I pass length as 1, why does this statement doesn't throws ArithmeticException
for 0 / 2.
I am missing out the core fundamental over here.
Please help me out here.
Here is the full code for reference:
public int solve(int A) {
if(A == 0)
return 0;
int result = 1;
int length = 1;
int count = 1;
while(count < A) {
length++;
count += (1 << ((length - 1) / 2));
}
count -= (1 << ((length - 1) / 2));
int offset = A - count - 1;
result |= (1 << (length - 1));
result |= offset << (length / 2);
int halfShiftedNumber = (result >> (length / 2));
int reversedNumber = getReversedNumber(halfShiftedNumber);
result |= reversedNumber;
return result;
}
int getReversedNumber(int A) {
int result = 0;
while(A > 0) {
int lsb = (A & 1);
result |= lsb;
result = result << 1;
A = A >> 1;
}
result = result >> 1;
return result;
}
What if I pass 1 as an input to the function.. it should throw ArithmeticException.
But its not..
Can anyone help me, explaining this basic stuff.
Thanks!
question from:
https://stackoverflow.com/questions/66056307/left-shift-operator-java-how-does-0-2-doesnt-throws-error 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…