Day 29: Bitwise AND
Day 29: Bitwise AND
+ 0 comments for one liner gang !!!!!!!!!!!!!!!!!!!!!!!!!!
def bitwiseAnd(N, K): return K - 1 if (K - 1 | K <= N) else K - 2
+ 0 comments In C++ was easy, but in python better dont use itertools combinations only double while.
+ 0 comments Java
Here is a very simple solution with the help of JAVA
class Result { /* * Complete the 'bitwiseAnd' function below. * * The function is expected to return an INTEGER. * The function accepts following parameters: * 1. INTEGER N * 2. INTEGER K */ public static int bitwiseAnd(int N, int K) { int cont=0; for(int i=1; i<=N; i++){ //outer loop for(int j=i+1; j<=N; j++){ //inner loop if((i&j) < K){ //condition to check the BITAND less then the //the given number if((i&j)>cont){ //to compare max and store it cont = (i&j); } } } } return cont; } }
+ 0 comments Java
Here is a very simple solution with the help of JAVA
class Result { /* * Complete the 'bitwiseAnd' function below. * * The function is expected to return an INTEGER. * The function accepts following parameters: * 1. INTEGER N * 2. INTEGER K */ public static int bitwiseAnd(int N, int K) { int cont=0; for(int i=1; i<=N; i++){ //outer loop for(int j=i+1; j<=N; j++){ //inner loop if((i&j) < K){ //condition to check the BITAND less then the //the given number if((i&j)>cont){ //to compare max and store it cont = (i&j); } } } } return cont; } }
+ 0 comments Python 3
TL;DR
def bitwiseAnd(N, K): while K > 0: K -= 1 tested = K+(1<<list(reversed(f'{K:b}')).index('0')) if "0" in f"{K:b}" else K+(1<<len(f'{K:b}')) if tested <= N : return K
Pros: get solution in max 2 iterations (if I'm not wrong)
In details
As example: given K=180. (K-1) = 179 = b
10110011
Find int
X
, thatX & 179 = 179
:- K-1= 179: b
10110011
- X1 = 183: b
10110111
- X2 = 191: b
10111111
- X3 = 255: b
11111111
- and
- X4 = 511: b
111111111
(note additional leading1
)
0 is inside binary (K-1). Replace 0 by 1. In most cases binary representation of
K-1
has few0
inside, like in our example: (K-1) = 179 is b10110011
. In such cases take 1st candidate 183 b10110111
. Test if 183 is less or equalN
. If True, then 179 is the answer. If False, no need to test other candidates (191,255,511), because they are defenetly greater thatN
.No 0 is inside binary (K-1). Add leading 1 to binary representation. This is edge case, when binary representation of
K-1
is all1
only. Exampe: K=256, K-1=255: b11111111
(8x1). In this case you need to test if 511: b111111111
(9x1) is less or equalN
. If True then 255 is the answer.If above test yield False, reduce
N
by 1 and repeat the test.Happy pythoning!
🦁
- K-1= 179: b
Sort 399 Discussions, By:
Please Login in order to post a comment