[해커랭크] 코딩테스트 문제 시도 [Java Datatypes] [x point]
[해커랭크] 코딩테스트 문제 시도 [nn번] [해결 =? O/X]
"풀이" 가 아닌 "시도" 를 추구합니다.

풀이 환경
언어 버전 : Java8
사용 패키지 : x
문제 요약
뭐 대충 자바 데이터 타입에는 char, boolean, byte, short, int, long, float, double 8가지가 있는데 여기서 숫자 T 를 입력받을거래용
그리고 byte, short, int, long 차례대로 8bit, 16bit, 32bit, 64bit 라고 합니당
아 이거 벌써부터 머리속 하얗게 만드네요... 자고싶다... 한 문제만 풀고 자야겠지 ?
나의 코드 및 나의 해설
일단 자바에서 데이터 타입을 어떻게 확인해야 하는 지 알아봐야 한다.
변수명.getClass().getName() 아옹 길어 ~~
다른 건? isinstance 연산자이당.
그럼 일단 하나씩 확인해보자
자 근데 여기서
long x = sc.nextLong();
System.out.println(x.getClass().getName());
이렇게 작성할라 했다면 분명 빨간줄이 떡하니 떴을 것이다.
자바는 무슨 언어다? 객체지향언어다.
저 getClass().getName() 이나 isinstance() 나 primitive 인 수에는 사용할 수 없다. 객체에만 가능하다.
그렇다면 객체로 어떻게 변환할 것인가?
System.out.println(((Object) x).getClass().getName());
요렇게 변환해주면
java.lang.Long
요렇게 나올 것이당 하지만 출력하려면 Long 만 나와야 한다.
getSimpleName() 으로 하면 된단다. (뭐가 이리 많아 ㅠㅠ)
일단 타입을 확인하는 다양한 방법들이 있지만 하나만 파보자.
원래 if - else 로 타입 하나씩 다 적고 출력해줄라 했는데... -150 이면 short 도 되고 int 도 되고 long 도 되네..
switch - case 문 이용하려 했는데 이것도 애매하다...
그냥 무작정 작성해본다.
import java.util.*;
import java.io.*;
class Solution{
public static void main(String []argh)
{
Scanner sc = new Scanner(System.in);
int t=sc.nextInt();
for(int i=0;i<t;i++)
{
try
{
long x=sc.nextLong();
System.out.println(x+" can be fitted in:");
if(x>=-128 && x<=127)System.out.println("* byte");
//Complete the code
if(((Object)(x)).getClass() == (Byte.class) ) {
System.out.print("byte");
} if (((Object)(x)).getClass() == (Short.class)) {
System.out.print("short");
} if (((Object)(x)).getClass() == (Integer.class)) {
System.out.print("int");
} if (((Object)(x)).getClass() == (Long.class)) {
System.out.print("long");
} else {
System.out.print("");
}
}
catch(Exception e)
{
System.out.println(sc.next()+" can't be fitted anywhere.");
}
}
}
}
결과는 nope , long 만 나온다...
이거는 아무래도 구글의 힘을 빌려야겠는 걸 ~?
import java.util.*;
import java.io.*;
class Solution{
public static void main(String []argh)
{
Scanner sc = new Scanner(System.in);
int t=sc.nextInt();
for(int i=0;i<t;i++)
{
try
{
long x=sc.nextLong();
System.out.println(x+" can be fitted in:");
if(x>=-128 && x<=127)System.out.println("* byte\n");
if(x>=Short.MIN_VALUE && x<=Short.MAX_VALUE)System.out.print("* short\n");
if(x>=Integer.MIN_VALUE && x<=Integer.MAX_VALUE)System.out.print("* int\n");
if(x>=Long.MIN_VALUE && x<=Long.MAX_VALUE)System.out.print("* long\n");
}
catch(Exception e)
{
System.out.println(sc.next()+" can't be fitted anywhere.");
}
}
}
}
일단, 자세히보니까 if(x>-128 && x<=127) System.out.println("* byte") 이 코드는 그냥 대놓고 준거였다..
원래 비트 수로 계산해서 하려고 했는데 자바에는.. 좋은 함수가 많더라 Short.MIN_VALUE 요런거...
이거까지는 사실 시간 쓰면서 문제를 푸려고 하기 보다는 인터넷 검색해서 빨리 습득하는 게 좋을 것 같단 생각이... !
아잇 당연히 통과할 줄.. 뭘 놓쳤을까
아니 너무 궁금해가지 hidden 풀었더니 다른 게 byte 출력 후에 줄바꿈이 한 번 더 일어나더라. .
\n 제거했더니 통과함 ..ㅎㅎ
문제 해답 풀이와 비교
대부분 비슷하다.
for (int i = 0; i < t; i++) {
try {
long x = sc.nextLong();
System.out.println(x + " can be fitted in:");
if (x >= -128 && x <= 127)
System.out.println("* byte");
if (x >= -32768 && x <= 32767)
System.out.println("* short");
if (x >= -2147483648 && x <= 2147483647)
System.out.println("* int");
System.out.println("* long");
} catch (Exception e) {
System.out.println(sc.next() + " can't be fitted anywhere.");
}
}
sc.close();
}
이렇게 쓰기도 함! 개념적으로도 알면 도움될 듯??
시간복잡도 및 공간복잡도 비교
x
놓친 부분과 배운 개념
[JAVA] - 변수 타입 확인 방법
변수 타입 찾기 자바 진영에선 기본적으로 객체 지향 프로그래밍 언어이기 때문에 int형이나 double형 같은 primitive 타입은 Wrapper 클래스 타입으로 확인할 수 밖에 없습니다. Object 클래스의 getClass()
namji9507.tistory.com
한글 주석 시 오류 발생
https://velog.io/@kafkaaaa/AOJ-HackerRank
[AOJ] HackerRank 오류 "Your submission contains non ASCII characters, we dont accept submissions with non ASCII characters for
온라인 저지 사이트 HackerRank 에서위와 같은 오류가 발생했다면!! 당신 코드의 문제가 아닐 수도 있다...😮 한글 주석을 지우고 실행
velog.io