- Prepare
- Algorithms
- Bit Manipulation
- AND Product
- Discussions

# AND Product

# AND Product

+ 0 comments SIMPLEST SOLUTION ->>>>>>>>>No headache!

long andProduct(long a, long b) {

`long c=a; for(long i=a+1;i<=b;i++) c=c&i; return c;`

}

+ 0 comments JAVASCRIPT Solution: In case any optimization can be made, do let me know :

function andProduct(a, b) { let A = a.toString(2); let B = b.toString(2); if (A.length !== B.length) return 0; else { let result = ''; let swap = false; for (let i = 0; i < A.length; i++){ if (A[i] !== B[i]) { swap = true; result += '0'; } if(A[i] == '1' && B[i] == '1') { if (swap == false) result += '1'; else result += '0'; } else if (A[i] == '0' && B[i] == '0') { result += '0'; } } return parseInt(result, 2); } }

+ 0 comments public static long andProduct(long a, long b) { // Write your code here return b & ((-(1 << (32-Long.numberOfLeadingZeros(a ^ b)))-1)+1); }

+ 0 comments My reasoning for this question is, For every binary number in the sequence you need them to be atleast a, which are the most significant bits, like first two bits that add up to 12 (8 + 4) in 12, 13, 14, 15. And these bits must occur in every number of this sequence(which is why and'ing cannot delete them). With certain code blocks you can cut out this part and add trailing zero bits to find the answer. The question is over at this point but if you wonder why we didn't include other bits, you need to constantly flip them to create different numbers this is why they are not consistent and will be deleted by bitwise and. Fun fact: if you have any element which is pow(2, x) and bigger than at least one element in the sequence then your answer will be certainly 0 because none of the below elements will use it's bit. Like 15 and 16, 01111 and 10000, no matter how you and them, the following result will be all zeros, and this will make all problem to collapse. This question only weights your understanding of bits, you don't need any tricks to solve it.

def andProduct(a, b): # Write your code here a = str(bin(a))[2:] b = str(bin(b))[2:] c = 0 print(a) print(b) for i in range(len(a)): if (a[i] == b[i] and a[i] == "1"):#to make sure that length of a and b are the same, to put it in a different way, we won't be affected by leading zeroes c = i break res = "" for i in range(c, len(a)): if (a[i] == b[i]):#cutting out the part that every number must consistently include res = res + a[i] else: break binary = res for i in range(len(a)-len(res)):#filling the right side with zeroes to make sure that bin -> int conversion will be accomplished right binary = binary + "0" binary = int(binary, 2) return binary

+ 1 comment Python version:

return a & ~((1<<(len(bin(a^b)) - 3)) - 1)

Sort 187 Discussions, By:

Please Login in order to post a comment