본문 바로가기
코딩 공부방 👩‍💻👨‍💻/알고리즘

[Java] 해커랭크(HackerRank) : Java Datatypes

by ByJinnie 2023. 2. 4.
반응형

[문제] 

조건문을 연습하는 문제입니다. 숫자가 입력되면 그 크기가 어떤 데이터 타입을 나타내는지 출력해야 합니다.

try-catch문을 활용해서 , 어떠한 데이터 타입에도 해당하지 않으면 'n can't be fitted anywhere.'가 출력됩니다.

각 데이터 타입의 크기는 문제에 명시돼 있습니다. (byte: 8-bit, short: 16-bit, int: 32-bit, long: 64-bit)

 

예시)

입력값 :

5
-150
150000
1500000000
213333333333333333333333333333333333
-100000000000000

 

출력값:

-150 can be fitted in:
* short
* int
* long
150000 can be fitted in:
* int
* long
1500000000 can be fitted in:
* int
* long
213333333333333333333333333333333333 can't be fitted anywhere.
-100000000000000 can be fitted in:
* 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 >= -Math.pow(2, 7) && x <= Math.pow(2, 7) - 1) {
                    System.out.println("* byte");
                }
                
                // Complete the code
                if (x >= -Math.pow(2, 15) && x <= Math.pow(2, 15) - 1) {
                    System.out.println("* short");
                }
                
                if (x >= -Math.pow(2, 31) && x <= Math.pow(2, 31) - 1) {
                    System.out.println("* int");
                }
                
                if (x >= -Math.pow(2, 63) && x <= Math.pow(2, 63) - 1) {
                    System.out.println("* long");
                }
                
            }
            catch(Exception e)
            {
                System.out.println(sc.next()+" can't be fitted anywhere.");
            }

        }
    }
}

 

* 문제 출처 (Prepare > Java > Introduction > Java Datatypes)

: https://www.hackerrank.com/

 

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

 

반응형

댓글