https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AXRSXf_a9qsDFAXS 

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com


풀이 과정

N과 M이 주어질 때, M의 이진수 표현의 마지막 비트 N자리가 모두 1인지를 판별하는 문제이다.

 

N자리가 모두 1로 차있는 이진수 T를 고려해보자. M과 T를 OR 연산을 시행했을때, M의 마지막 비트 N자리중에 0인 비트는 1로 바뀌게 되어 M은 다른 숫자로 변하게 된다. 따라서 N자리가 모두 1일때만 OR 연산을 시행 후에도 M의 값이 변하지 않게 됨을 이용해 비트마스킹으로 문제를 해결할 수 있다.


소스 코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int T = Integer.parseInt(br.readLine());

        for (int tc = 1; tc <= T; tc++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            int N = Integer.parseInt(st.nextToken());
            int M = Integer.parseInt(st.nextToken());
            if ((M | ((1 << N)) - 1) == M) { // M과, 마지막 N비트에 1을 채운 수를 OR 연산한 값이 M이면, M의 마지막 N비트는 모두 1이다. 
                // 마지막 N비트에 1이 아닌 수가 있다면, OR 연산 이후에 1로 바뀌고, 기존의 M과 다른 수가 된다.
                System.out.printf("#%d %s\n", tc, "ON"); // 따라서 ON이다.
            } else {
                System.out.printf("#%d %s\n", tc, "OFF"); // 아니면 OFF다.
            }
        } // end of testcase
    } // end of main
} // end of class

 

+ Recent posts