## Amazon Interview Question

Software Engineer / Developers**Country:**United States

**Interview Type:**Phone Interview

Yes i figured this out eventually after the interview when i sat and wrote all the steps.

You want to check that "number AND k" preserves k

```
boolean isSet1(int number, int pos) {
int k = 1;
for(int i = 1; i <= pos; i++) {
k = k << 1;
}
return (number & k) == k;
}
```

That would require number to be a power of 2. If you '&k', it will erase the other bits of number except for the one at pos.

One way is :

```
public static boolean isBitSet(int n, int pos) {
return ((n & (1 << pos)) > 0);
}
```

another way is

```
public static boolean isBitSet(int n, int pos) {
return (((n >> pos) & 1) == 1);
}
```

bit position start at 0.

One example is the number 15 and we want to know if the bit in the position 3 is on, so the binary number for 15 is 00001111, so what the method does is turn the bit in the given position creating this number 00001000 then it does an AND of 00001111 & 00001000 which should give us the same number 00001000 as a result. If the bit asked were 0 and let's say the given number was 7 instead, which is 00000111, then when doing 00000111 & 00001000 the result would be 0, makes sense?

probably you can just divide num by 2 for position number of times and then take num % 2.

if the result is 1 then return true else return false.

```
1 #include<stdio.h>
2
3 int bitSet(int num,int pos)
4
5 {
6
7 if((num &(1<<(pos-1))))
8
9 return 1;
10
11 else
12 return 0;
13
14 }
15
16
17 int main()
18
19
20 {
21
22 int num,pos;
23
24 printf("Enter the Number ");
25
26 scanf("%d",&num);
27
28 printf("Enter the position :");
29
30 scanf("%d",&pos);
31
32 if(bitSet(num,pos))
33
34 printf("True");
35
36 else
37 printf("False");
38
39
40
41 }
```

k = 1 << pos

- Anonymous April 05, 2012return ((number & k) > 0)

number & k may not be 1

number = 100

pos = 3

100 & 100 = 100 (4) not 1