22.4.20 [HackerRank]Java Int to String

서태욱·2022년 4월 20일
0

Algorithm

목록 보기
9/45
post-thumbnail

🌱 배경지식

int -> String 변환

1) Integer.toString()
Integer 클래스의 toString() method를 사용한다.

public class IntToString {
	public static void main(String[] args) {
		int a = 123;
        
		String string = Integer.toString(a);
        
		System.out.println(string);
  }
}

2) String.valueOf()
java.lang.String 클래스의 valueOf() method를 사용한다.

public class IntToString {
	public static void main(String[] args) {
		int a = 123;
        
		String string = String.valueOf(a);
        
		System.out.println(string);
  }
}

3) "" + n
java에서 문자열 오른쪽에 + operator를 붙이면(연산을 가하면) 새로운 문자열이 return 되는 속성을 이용한다.

The + operator, when used on the right side of a String, simply connects stuff to the right of the original String. If what it's connecting is not yet a String, it automatically converts it into one, which is what we want for this exercise.

public class IntToString {
	public static void main(String[] args) {
		int a = 123;
        
		String string = "" + a;
        
		System.out.println(string);
  }
}

✏️ 해설 및 분석

import java.util.*;
import java.security.*;
public class Solution {
 public static void main(String[] args) {

  DoNotTerminate.forbidExit();

  try {
   Scanner in = new Scanner(System.in);
   int n = in .nextInt();
   in.close();
   //String s=???; Complete this line below

   //Write your code here
   String s = Integer.toString(n);
   
   
   if (n == Integer.parseInt(s)) {
    System.out.println("Good job");
   } else {
    System.out.println("Wrong answer.");
   }
  } catch (DoNotTerminate.ExitTrappedException e) {
   System.out.println("Unsuccessful Termination!!");
  }
 }
}

//The following class will prevent you from terminating the code using exit(0)!
class DoNotTerminate {

 public static class ExitTrappedException extends SecurityException {

  private static final long serialVersionUID = 1;
 }

 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);
 }
}

👉 참고

profile
re:START

0개의 댓글