A and B are non negative.
#include <iostream>
using namespace std;
int main() {
cout << sizeof(long long unsigned) << endl;
cout << sizeof(int) << endl;
int a = 0x01111111;
int b = 0x01111111;
long long unsigned c = a * b;
cout << c << endl;
long long unsigned x = 0x01111111;
long long unsigned y = 0x01111111;
long long unsigned z = x * y;
cout << z << endl;
return 0;
}
result
8
4
1734689569
320255971115809
I guess
Maybe you need to convert a and b into long long before mutiplying them.
@Acer why A, B signed but C unsigned ?
A and B are non negative.
>"I only got 50% of the test cases passed."
Does this mean that 50% produced an error, or that 50% produced the wrong result?
Just looking at it without actually testing it myself, I suspect the problem is in the divide by 2, (C/=2;) which would be a non-integer result about 50% of the time.
Perhaps a better way is to use bitwise operators. Use bitwise shift left (<<) and then test if it is greater than 2^(n-1). (where n=number of bits). Or optionally, after the shift do a logical AND (&) with a mask that has the highest bit set, then compare, etc.
There was a time-limited online assessment. When I submitted this solution, I passed 6 test cases of 12 test cases.
it is C++ clode, C/=2 would be a non-integer result because C is not of doubel type.
Yea, using bitwise operators is better.
the range of A and B is [0,1000000000]
I dont understand the after-the-shift part.
For example, after the shift left, if you want to test the MSB (most-significant bit) of an 8-bit result that looks like this:
10011000
You could do a logical AND with a mask that looks like this:
10000000 , which is 2^(8-1)
The result is zero if the MSB is zero.
There may be a specific C++ operation that can directly check the MSB without using the mask, but I don't remember if there is or not.
Note: The 2^(n-1) allows for an arbitrary number of bits, but you'd probably know that already in advance and could just use a constant.
Also, yes, the test would come before the shift, unless you were testing the carry flag, but I don't think C can do that.
I think shrik3's solution is the most efficient -- shift right, use the LSB (least significant bit), mask with "1", then no need to test/compare since the result of the mask is all ready to add to the count.
Good job shrik3!
Trying to think of applications of that function... error detection, image processing, and maybe signal processing? I don't know...