Programming/Algorithm

[Java] μžλ°”μ˜ 이진 μ—°μ‚°(λΉ„νŠΈ μ—°μ‚°)

Space_Jin 2025. 4. 6. 23:33
728x90
λ°˜μ‘ν˜•
OR μ—°μ‚°κ³Ό AND μ—°μ‚°

OR 연산은 μ΄μ§„μˆ˜μ˜ 각 μžλ¦¬μˆ˜κ°€ ν•˜λ‚˜λΌλ„ 1이면 ν•΄λ‹Ή μžλ¦Ώμˆ˜λŠ” 1, μ•„λ‹ˆλ©΄ 0을 리턴

AND 연산은 μ΄μ§„μˆ˜μ˜ 각 자리수 λͺ¨λ‘κ°€ 1이면 ν•΄λ‹Ή μžλ¦Ώμˆ˜λŠ” 1, μ•„λ‹ˆλ©΄ 0을 리턴

 public static void main(String []args) {
    int n1 = 4; // 100
    int n2 = 5; // 101

    // OR μ—°μ‚°
    int n3 = n1 | n2;   // 101 -> 5
    // AND μ—°μ‚°
    int n4 = n1 & n2;   // 100 -> 4

    System.out.println(n3);
    System.out.println(n4);
 }

 

μ‹œν”„νŠΈ μ—°μ‚°

μ΄μ§„μˆ˜μ˜ λΉ„νŠΈλ₯Ό μ›ν•˜λŠ” κ°’λ§ŒνΌ μ΄λ™μ‹œν‚€λŠ” μ—°μ‚°

 public static void main(String []args) {
    int n1 = 4; // 100
    int n2 = 5; // 101

    // << μ™Όμͺ½ μ‹œν”„νŠΈ
    int n3 = n1 << 2;   // 100을 μ™Όμͺ½μœΌλ‘œ λ‘μžλ¦¬λ§ŒνΌ 이동 -> 10000(16)

    // >> 였λ₯Έμͺ½ μ‹œν”„νŠΈ
    int n4 = n2 >> 1;   // 101을 였λ₯Έμͺ½μœΌλ‘œ ν•œμžλ¦¬λ§ŒνΌ 이동 -> 10(2)

    System.out.println(n3);
    System.out.println(n4);
 }

 

μ΄μ§„μˆ˜ λ¬Έμžμ—΄μ„ int둜 λ³€ν™˜
public static void main(String []args) {
    int n = stringToInt("100"); // 4
    System.out.println(n);
    n = stringToInt("101"); // 5
    System.out.println(n);
 }

// μ΄μ§„μˆ˜ ν˜•μ‹μ˜ λ¬Έμžμ—΄μ„ int둜 계산
static int stringToInt(String bitString) {
	int result = 0;
	for(int i=0; i<bitString.length(); i++) {
		if(bitString.charAt(i) == '1') {
        	// OR μ—°μ‚°κ³Ό μ‹œν”„νŠΈ μ—°μ‚°
			result |= (1 << (bitString.length() - 1 - i));
		}
	}
	return result;
}

 

XOR μ—°μ‚°

μ΄μ§„μˆ˜μ˜ κ°’μ˜ 각 μžλ¦Ώμˆ˜κ°€ μ„œλ‘œ λ‹€λ₯Ό 경우, 1

 public static void main(String []args) {
    int n1 = 4; // 100
    int n2 = 5; // 101

    // XOR μ—°μ‚°
    int n3 = n1 ^ n2;   // 001(1)

    // μžλ¦Ώμˆ˜κ°€ λ‹€λ₯Έ 경우, XOR μ—°μ‚°
    n1 = 8; // 10000
    int n4 = n1 ^ n2;   // 1000 ^ 101 = 1101(13)

    System.out.println(n3);
    System.out.println(n4);
 }

 

μ΄μ§„μˆ˜ κ°’μ˜ 각 자릿수 μ€‘μ˜ 1의 개수 κ΅¬ν•˜κΈ° / Brian Kernighan's Algorithm

 

Brian Kernighan's Algorithm의 μ›λ¦¬λŠ” λ‹€μŒκ³Ό κ°™λ‹€

n-1의 값은 n이 κ°€μ§€κ³  μžˆλŠ” κ°€μž₯ 였λ₯Έμͺ½μ— 1λΆ€ν„° 값이 λ³€ν•œλ‹€.

μ˜ˆμ‹œ. n = 10100 -> n-1 = 10011

 

이후 두 값을 ANDμ—°μ‚°μž n & (n - 1) ν•΄μ£Όλ©΄, 10000되며 κ°€μž₯ 였λ₯Έμͺ½μ— μžˆλŠ” 1이 μ œκ±°λœλ‹€.

이 연산을 λ°˜λ³΅ν•˜μ—¬ μ΅œμ’…μ μœΌλ‘œ 값이 0이 λœλ‹€λ©΄, λ°˜λ³΅ν•œ μ—°μ‚°μ˜ κ°œμˆ˜λŠ” n이 κ°€μ§€κ³ μžˆλ˜ 1의 κ°œμˆ˜μ™€ κ°™λ‹€.

public static void main(String []args) {
    int n1 = 4; // 100
    int n2 = 5; // 101
    int n3 = 7; // 111

    System.out.println(BKA(n1));    // 1
    System.out.println(BKA(n2));    // 2
    System.out.println(BKA(n3));    // 3
 }

 // Brian Kernighan's Algorithm
 static int BKA(int n) {
    int cnt = 0;

    while(n > 0) {
        n &= (n - 1);
        cnt++;
    }
    return cnt;
 }
728x90
λ°˜μ‘ν˜•