728x90
반응형
해커랭크 - https://www.hackerrank.com/
Prepare > Java > Advanced > Can You Access?
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
반응형
'> 개발-IT-인터넷 > > JAVA' 카테고리의 다른 글
[해커랭크(HackerRank) JAVA 풀이] - Java Factory Pattern (0) | 2023.11.22 |
---|---|
[해커랭크(HackerRank) JAVA 풀이] - Prime Checker (1) | 2023.11.20 |
[해커랭크(HackerRank) JAVA 풀이] - Java Reflection - Attributes (0) | 2023.11.07 |
[해커랭크(HackerRank) JAVA 풀이] - Java Varargs - Simple Addition (0) | 2023.11.06 |
[해커랭크(HackerRank) JAVA 풀이] - Java Exception Handling (1) | 2023.11.02 |