문제 설명

주어진 정수 A와 B를 이진수로 표현했을 때, A를 B로 바꾸기 위하여 뒤집어야 하는 비트의 개수를 구하는 프로그램을 작성하세요.

여기서 비트를 뒤집는 것은 0 → 1, 1 → 0으로 변환하는 것을 말합니다.


입력 형식

· A, B : 양의 정수


출력 형식

· A를 B로 바꾸기 위해 뒤집어야 하는 비트의 개수


제약 사항

· 0 <= A, B <= 100


입출력 예시

· 입력

  · A = 29

  · B = 15

· 출력 : 2

· 설명 : A와 B를 이진수로 표현하면 아래와 같다. A를 B로 바꾸기 위해서는 총 2개의 비트를 뒤집으면 된다.

  · A = 0b11101

  · B = 0b01111


작성 코드

class Solution234 {
    public int solution(int A, int B) {
        int xor = A ^ B; // A와 B의 비트 차이를 계산하기 위해 XOR 연산 수행
        int count = 0;
        while (xor != 0) { // xor이 0이 될 때까지 반복
            if ((xor & 1) == 1) { // 마지막 비트가 1이면 뒤집어야 함
                count++;
            }
            xor = xor >> 1; // 다음 비트를 검사하기 위해 오른쪽으로 한 칸 시프트
        }
        return count;
    }

    public static void main(String[] args) {
        Solution234 st = new Solution234();
        int A = 29;
        int B = 15;
        System.out.println(st.solution(A, B));
    }
}

 

정답 코드

class Solution {
    public int solution(int A, int B) {
        int val = A ^ B;
        int result = 0;
        while (val > 0) {
            if (val % 2 == 1) {
                result++;
            }
            val /= 2;
        }
        return result;
    }

    public static void main(String[] args) {
        Solution st = new Solution();
        int A = 29;
        int B = 15;
        System.out.println(st.solution(A, B));
    }
}