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!
0 / NaturalNumber
is a valid mathematical operation that will result a 0
. So programming languages support the operation. (this applies to negative and floating point numbers too)
In the related context, 0
as denominator is undefined.
So, for AnyNumber / 0
operation, programming languages can throw exception.
Please be aware that when length is zero or negative (so that length-1
is negative), then it will result in unexpected result.
somenumber << -value
is similar to somenumber << ((32 - value) % 32)
somenumber << -value
is similar to somenumber << ((64 - value) % 64)