> 개발-IT-인터넷/> JAVA

[해커랭크(HackerRank) JAVA 풀이] - Can You Access?

jini:) 2023. 11. 13. 14:29
728x90
반응형
해커랭크 - https://www.hackerrank.com/
Prepare > Java > Advanced > Can You Access?
 

HackerRank

HackerRank is the market-leading technical assessment and remote interview solution for hiring developers. Learn how to hire technical talent from anywhere!

www.hackerrank.com

 

 

Solution 클래스와 Inner.Private 내부 클래스가 제공됩니다. Solution 클래스의 주요 메서드는 정수 num을 입력으로 사용합니다. Inner.Private 클래스의 powerof2는 숫자가 2의 거듭제곱인지 확인합니다. Solution 클래스의 기본 메서드에서 Inner.Private 클래스의 powerof2 메서드를 호출해야 합니다.

 

Constraints

1 ≤ num ≤ 2³⁰

 

Sample Input

8

 

Sample Output

8 is power of 2
An instance of class: Solution.Inner.Private has been created

 

 

Code

import java.io.*;
import java.lang.reflect.*;
import java.util.*;
import java.util.regex.*;
import java.security.*;


public class Solution {

	public static void main(String[] args) throws Exception {
		DoNotTerminate.forbidExit();	

		try{
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			int num = Integer.parseInt(br.readLine().trim());
			Object o;// Must be used to hold the reference of the instance of the class Solution.Inner.Private

			//Write your code here
            Class inner = Class.forName("Solution$Inner");
            Class priv = Class.forName("Solution$Inner$Private");
            Constructor con = priv.getDeclaredConstructor(inner);
            con.setAccessible(true);
            o = con.newInstance(inner.newInstance());
            Method method = priv.getDeclaredMethod("powerof2",int.class);
            method.setAccessible(true);
            System.out.println(String.valueOf(num)+" is "+method.invoke(o,num));

		System.out.println("An instance of class: " + o.getClass().getCanonicalName() + " has been created");
		
		}//end of try
		
		catch (DoNotTerminate.ExitTrappedException e) {
			System.out.println("Unsuccessful Termination!!");
		}
	}//end of main
	static class Inner{
		private class Private{
			private String powerof2(int num){
				return ((num&num-1)==0)?"power of 2":"not a power of 2";
			}
		}
	}//end of Inner
	
}//end of Solution

class DoNotTerminate { //This class prevents exit(0)
	 
    public static class ExitTrappedException extends SecurityException {

		private static final long serialVersionUID = 1L;
    }
 
    public static void forbidExit() {
        final SecurityManager securityManager = new SecurityManager() {
            @Override
            public void checkPermission(Permission permission) {
                if (permission.getName().contains("exitVM")) {
                    throw new ExitTrappedException();
                }
            }
        };
        System.setSecurityManager(securityManager);
    }
}

 

 

 

개인 공부를 위한 포스팅입니다.
모든 번역, 코드는 완벽하지 않을 수 있습니다.

 

 

 

728x90
반응형