|
| 1 | +package bit; |
| 2 | +import org.junit.Test; |
| 3 | + |
| 4 | + |
| 5 | +import static org.hamcrest.CoreMatchers.is; |
| 6 | +import static org.junit.Assert.assertThat; |
| 7 | + |
| 8 | +public class BitOperator { |
| 9 | + |
| 10 | + @Test |
| 11 | + public void test() { |
| 12 | + assertThat(isPowerOf2(2), is(true)); |
| 13 | + assertThat(isPowerOf2(4), is(true)); |
| 14 | + assertThat(isPowerOf2(8), is(true)); |
| 15 | + assertThat(isPowerOf2(16), is(true)); |
| 16 | + assertThat(isPowerOf2(17), is(false)); |
| 17 | + } |
| 18 | + |
| 19 | + public String testFunction() { |
| 20 | + return ""; |
| 21 | + } |
| 22 | + |
| 23 | + public boolean get(int n, int i) { |
| 24 | + int mask = 1 << i; |
| 25 | + return (n & mask) != 0; |
| 26 | + } |
| 27 | + |
| 28 | + public int set(int n, int i) { |
| 29 | + int mask = 1 << i; |
| 30 | + return n | mask; |
| 31 | + } |
| 32 | + |
| 33 | + public int clear(int n, int i) { |
| 34 | + int mask = ~(1 << i); |
| 35 | + return n & mask; |
| 36 | + } |
| 37 | + |
| 38 | + /* |
| 39 | + TASK |
| 40 | + 2의 제곱수인지 판별한다. |
| 41 | + */ |
| 42 | + |
| 43 | + public boolean isPowerOf2(int n) { |
| 44 | + // 10 == 2 => 2 - 1 == 1 |
| 45 | + // 100 == 4 => 4 - 1 == 11 |
| 46 | + // 1000 == 8 => 8 - 1 == 111 |
| 47 | + // 10000 == 16 => 16 - 1 == 1111 |
| 48 | + // n에서 1을 뺀다음에 n과 and 연산을 하면 모두 0이 된다. |
| 49 | + return (n & (n - 1)) == 0; |
| 50 | + } |
| 51 | + |
| 52 | + /* |
| 53 | + TASK |
| 54 | + 두 수에서 다른 비트의 개수를 구한다. |
| 55 | + */ |
| 56 | + |
| 57 | + public int getBitDiff(int a, int b) { |
| 58 | + int diff = a ^ b; //XOR |
| 59 | + int count = 0; |
| 60 | + while (diff != 0) { |
| 61 | + diff = diff & (diff - 1); |
| 62 | + count++; |
| 63 | + } |
| 64 | + return count; |
| 65 | + } |
| 66 | +} |
0 commit comments