Why is this code not giving expected value for n = 1000000000000
Expected value = 1099511627775
While the code is giving 255
long long now = n, count = 0, len = 0;
while (now >= 1) {
count++;
now /= 2;
}
len = (1 << count) - 1;
cout << len;
Why is this code not giving expected value for n = 1000000000000
Expected value = 1099511627775
While the code is giving 255
long long now = n, count = 0, len = 0;
while (now >= 1) {
count++;
now /= 2;
}
len = (1 << count) - 1;
cout << len;
In 1 << count
the constant 1
is an int
not a long long
.
Then the shift overflows.
You should use 1ll << count
.