- Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathBitOperator.java
More file actions
Latest commit
66 lines (54 loc) · 1.44 KB
/
Copy pathBitOperator.java
File metadata and controls
66 lines (54 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
packagebit;
importorg.junit.Test;
importstaticorg.hamcrest.CoreMatchers.is;
importstaticorg.junit.Assert.assertThat;
publicclassBitOperator {
@Test
publicvoidtest() {
assertThat(isPowerOf2(2), is(true));
assertThat(isPowerOf2(4), is(true));
assertThat(isPowerOf2(8), is(true));
assertThat(isPowerOf2(16), is(true));
assertThat(isPowerOf2(17), is(false));
}
publicStringtestFunction() {
return"";
}
publicbooleanget(intn, inti) {
intmask = 1 << i;
return (n & mask) != 0;
}
publicintset(intn, inti) {
intmask = 1 << i;
returnn | mask;
}
publicintclear(intn, inti) {
intmask = ~(1 << i);
returnn & mask;
}
/*
TASK
2의 제곱수인지 판별한다.
*/
publicbooleanisPowerOf2(intn) {
// 10 == 2 => 2 - 1 == 1
// 100 == 4 => 4 - 1 == 11
// 1000 == 8 => 8 - 1 == 111
// 10000 == 16 => 16 - 1 == 1111
// n에서 1을 뺀다음에 n과 and 연산을 하면 모두 0이 된다.
return (n & (n - 1)) == 0;
}
/*
TASK
두 수에서 다른 비트의 개수를 구한다.
*/
publicintgetBitDiff(inta, intb) {
intdiff = a ^ b; //XOR
intcount = 0;
while (diff != 0) {
diff = diff & (diff - 1);
count++;
}
returncount;
}
}