#9 Java Static Initializer Block

HackerRank/HR-Java 2015. 11. 23. 11:25 by 후뤼한잉여

https://www.hackerrank.com/challenges/java-static-initializer-block


Problem Statement

Static initialization blocks are executed when the class is loaded, and you can initialize static variables in those blocks.

It's time to test your knowledge of Static initialization blocks. You can read about it here.

You are given a class Solution with a main method. Complete the given code so that it outputs the area of a parallelogram with breadth B and height H. You should read the variables from the standard input.

If B0 or H 0, the output should be "java.lang.Exception: Breadth and height must be positive" without quotes.

Input Format

There are two lines of input. The first line contains B: the breadth of the parallelogram. The next line contains H: the height of the parallelogram.

Problem Statement

Static initialization blocks are executed when the class is loaded, and you can initialize static variables in those blocks.

It's time to test your knowledge of Static initialization blocks. You can read about it here.

You are given a class Solution with a main method. Complete the given code so that it outputs the area of a parallelogram with breadth B and height H. You should read the variables from the standard input.

If B0 or H 0, the output should be "java.lang.Exception: Breadth and height must be positive" without quotes.

Input Format

There are two lines of input. The first line contains B: the breadth of the parallelogram. The next line contains H: the height of the parallelogram.

Constraints 
100B100 
100H100

Output Format

If both values are greater than zero, then the main method must output the area of theparallelogram. Otherwise, print "java.lang.Exception: Breadth and height must be positive"without quotes.

Sample input 1

1
3

Sample output 1

3

Sample input 2

-1
2

Sample output 2

java.lang.Exception: Breadth and height must be positive

Copyright © 2015 HackerRank.

static 키워드에 대한 활용을 하는지에 대한 질문으로 Exception에 대해서 Exception으로 처리해야하는지 애를 먹었지만 알고보니 단순 프린트 하라는 거였음. B와 H값은 -100 ~ 100 사이의 정수로 제한된다. 영어 무식자라 처음엔 저 제약(Constraints)하는 부분이 개발자가 처리해야하는 거라 생각 했는데 문제를 풀다보니 테스트 케이스 입력 값을 저 제한된 값으로 보내주겠다는 의미인거 같다.

그래서 그 부분은 신경 안쓰고 에러 메세지에 따라 음수일 경우에만 에러를 출력하도록 했다.

이번 문제는 중간에 부분만 작성하도록 되어있어 그부분만 작성한다.


보낸 답)

    static private int B = 0;

    static private int H = 0;

    static private boolean flag = false;

    static {

        Scanner sc = new Scanner(System.in);

        B = sc.nextInt();

        H = sc.nextInt();


        if( (B <= 0) || (H <= 0)) {

            flag = false;

            System.out.println("java.lang.Exception: Breadth and height must be positive");

        } else {

            flag = true;

        }

    }


'HackerRank > HR-Java' 카테고리의 다른 글

#8 Java End-of-file  (0) 2015.11.23
#6 Java Loops  (0) 2015.11.18
#5 Java Output Formatting  (0) 2015.11.17
#4 Java Stdin and Stdout 2  (0) 2015.11.17
#3 Java If-Else  (0) 2015.11.17

#8 Java End-of-file

HackerRank/HR-Java 2015. 11. 23. 10:32 by 후뤼한잉여

https://www.hackerrank.com/challenges/java-end-of-file


Problem Statement

In computing, End Of File (commonly abbreviated EOF) is a condition in a computer operating system where no more data can be read from a data source. (Wikipedia)

Sometimes you don't know how many lines are there in a file and you need to read the file until EOF or End-of-file. In this problem you need to read a file until EOF and print the contents of the file. You must take input from stdin(System.in).

Hints: One way to do this is to use hasNext() function in java scanner class.

Input Format

Each line will contain a non-empty string. Read until EOF.

Output Format

For each line, print the line number followed by a single space and the line content.

Sample Input

Hello world
I am a file
Read me until end-of-file.

Sample Output

1 Hello world
2 I am a file
3 Read me until end-of-file

Copyright © 2015 HackerRank.


파일을 기본 입력으로 부터 받아 파일의 끝까지 아래와 같이 출력하시오.


보낸 답)

import java.util.Scanner;


public class Solution {


    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        

        int i = 0;

        while(sc.hasNext()) {

            i++;

            System.out.println(i + " " + sc.nextLine());

        }

    }

}



'HackerRank > HR-Java' 카테고리의 다른 글

#9 Java Static Initializer Block  (0) 2015.11.23
#6 Java Loops  (0) 2015.11.18
#5 Java Output Formatting  (0) 2015.11.17
#4 Java Stdin and Stdout 2  (0) 2015.11.17
#3 Java If-Else  (0) 2015.11.17

#6 Java Loops

HackerRank/HR-Java 2015. 11. 18. 00:38 by 후뤼한잉여

https://www.hackerrank.com/challenges/java-loops


Problem Statement

In this problem you will test your knowledge of Java loops. Given three integers ab, and n, output the following series:

a+20b,a+20b+21b,......,a+20b+21b+...+2n1b

Input Format

The first line will contain the number of testcases t. Each of the next t lines will have three integers, ab, and n.

Constraints:

0a,b50
1n15

0a,b50
1n15

Output Format

Print the answer to each test case in separate lines.

Sample Input

2
0 2 10
5 3 5

Sample Output

2 6 14 30 62 126 254 510 1022 2046
8 14 26 50 98

Explanation

In the first case:

1st term=0+1*2=2
2nd term=0+1*2+2*2=6
3rd term=0+1*2+2*2+4*2=14

and so on.

보낸 답)

테스트 케이스가 많으면 메모리를 많이 먹겠지만 초보니까 쿨하게 패스~!(+ 거기다 범위가 있었다는걸 나중에 깨달음...)

import java.util.*;

import java.math.*;


public class Solution {


    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        

        int testCaseCnt = sc.nextInt();

        int a[] = new int[testCaseCnt];

        int b[] = new int[testCaseCnt];

        int n[] = new int[testCaseCnt];

        int sum;

        

        for(int i=0; i<testCaseCnt; i++) {

            a[i] = sc.nextInt();

            b[i] = sc.nextInt();

            n[i] = sc.nextInt();

        }

        

        for(int i=0; i<testCaseCnt; i++) {

            sum = 0;

            

            for(int j=0; j<n[i]; j++) {

                if(j == 0) {

                    sum +=  a[i];

                }

                sum += (b[i] * (int)Math.pow(2,j));

                System.out.print(sum + " ");

            }

            System.out.println();

        }

    }

}




'HackerRank > HR-Java' 카테고리의 다른 글

#9 Java Static Initializer Block  (0) 2015.11.23
#8 Java End-of-file  (0) 2015.11.23
#5 Java Output Formatting  (0) 2015.11.17
#4 Java Stdin and Stdout 2  (0) 2015.11.17
#3 Java If-Else  (0) 2015.11.17

#5 Java Output Formatting

HackerRank/HR-Java 2015. 11. 17. 23:50 by 후뤼한잉여

https://www.hackerrank.com/challenges/java-output-formatting


Take exactly 3 lines of input. Each line consists of a string and an integer. Suppose this is the sample input:

java 100
cpp 65
python 50

The strings will have at most 10 alphabetic characters and the integers will range between 0 to 999.

In each line of output there should be two columns. The string should be in the first column and the integer in the second column. This is the output for the input above:

================================
java           100 
cpp            065 
python         050 
================================

The first column should be left justified using exactly 15 characters. The integer of the second column should have exactly 3 digits. If the original input has less than 3 digits, you should pad with zeros to the left.

To make the problem easier, some part of the solution is already given in the editor, just complete the remaining parts.


입력은 문자열은 최대 10자리, 정수형은 0부터 999로 입력이 된다.

출력시에는 첫번째 컬럼 즉 문자열은 15자리로 왼쪽 정렬이 되어야 하며, 두번째 컬럼 즉 정수형은 3자리여야 한다.

정수 값이 3자리 보다 작으면 왼쪽에 0으로 채운다.


보낸 답)

printf를 사용하여 문자열은 15자리인데 왼쪽정렬(-)을 하고(%-15s), 정수형은 3자리인데 앞에 부족한 부분은 0으로 채워놓는 형식(%03d)으로 해서 제출했다.

import java.util.Scanner;


public class Solution {

    public static void main(String[] args) {

            Scanner sc = new Scanner(System.in);

        

            System.out.println("================================");

            for(int i=0; i<3; i++){

                String s1 = sc.next();

                int x=sc.nextInt();

                System.out.printf("%-15s%03d\n",s1, x);

            }

            System.out.println("================================");


    }

}


'HackerRank > HR-Java' 카테고리의 다른 글

#8 Java End-of-file  (0) 2015.11.23
#6 Java Loops  (0) 2015.11.18
#4 Java Stdin and Stdout 2  (0) 2015.11.17
#3 Java If-Else  (0) 2015.11.17
#2 Java Stdin and Stdout 1  (0) 2015.11.17

#1 Revising the Select Query - 1

HackerRank/HR-SQL 2015. 11. 17. 11:52 by 후뤼한잉여

https://www.hackerrank.com/challenges/revising-the-select-query


Given a City table, whose fields are described as

+-------------+----------+
| Field       | Type     |
+-------------+----------+
| ID          | int(11)  |
| Name        | char(35) |
| CountryCode | char(3)  |
| District    | char(20) |
| Population  | int(11)  |
+-------------+----------+

write a query that will fetch all columns for every row in the table where the CountryCode = 'USA' (i.e, we wish to retreive data for all American cities) and the population exceeds 100,000.

City라는 테이블은 다음과 같은 명세로 주어져 있다.

모든 컬럼을 가져오는데 CountryCode는 USA로 하며 Population이 100,000 초과하는 도시에 대해서 조회하라는 듯 하다.


보낸 답)

SELECT  *

FROM    City

WHERE   CountryCode = 'USA'

AND     Population >= 100000;


#4 Java Stdin and Stdout 2

HackerRank/HR-Java 2015. 11. 17. 11:40 by 후뤼한잉여

https://www.hackerrank.com/challenges/java-stdin-stdout


Sample Input

42
3.1415
Welcome to Hackerrank Java tutorials!

Sample Output

String: Welcome to Hackerrank Java tutorials!
Double: 3.1415
Int: 42

정수, 실수, 문자열 순으로 입력받아 역순으로 출력하기.


보낸 답)

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {

            Scanner sc=new Scanner(System.in);

        

            int i = sc.nextInt();

            double d = sc.nextDouble();

            sc.nextLine();

            String s = sc.nextLine();

            

            System.out.println("String: " + s);

            System.out.println("Double: " + d);

            System.out.println("Int: " + i);

    }

}



'HackerRank > HR-Java' 카테고리의 다른 글

#6 Java Loops  (0) 2015.11.18
#5 Java Output Formatting  (0) 2015.11.17
#3 Java If-Else  (0) 2015.11.17
#2 Java Stdin and Stdout 1  (0) 2015.11.17
#1 Welcome to Java!  (0) 2015.11.17

#3 Java If-Else

HackerRank/HR-Java 2015. 11. 17. 00:23 by 후뤼한잉여

https://www.hackerrank.com/challenges/java-if-else


문제)

Given an integer N as input, check the following:

  • If N is odd, print "Weird".
  • If N is even and, in between the range of 2 and 5(inclusive), print "Not Weird".
  • If N is even and, in between the range of 6 and 20(inclusive), print "Weird".
  • If N is even and N>20, print "Not Weird".

We given you partially completed code in the editor, complete it to solve the problem.

Input Format

There is a single line of input: integer N.

Constraints 
1N100

Output Format

Print "Weird" if the number is weird. Otherwise, print "Not Weird". Do not print the quotation marks.


입력받은 N이 홀수이면 "Weird" 출력

N이 짝수면서 2~5 사이면 "Not Weird" 출력

N이 짝수면서 6~20 사이면 "Weird" 출력

N이 짝수면서 20보다 크면 "Not Weird" 출력


기본적으로 import 되어있는 라이브러리를 보면 정규식등 이용할 수 있게 한거 같은데 잘 모르니 무식하게 고


보낸 답)

  import java.util.Scanner;


    public class Solution {

        public static void main(String[] args) {


            Scanner sc = new Scanner(System.in);

            int n = sc.nextInt();

            String ans = "";

            

            if(n%2 == 1) {

                ans = "Weird";

            } else if(n > 20) {

                ans = "Not Weird";

            } else if(n > 6) {

                ans = "Weird";

            } else {

                ans = "Not Weird";

            }

            

            System.out.println(ans);

        }

    }


'HackerRank > HR-Java' 카테고리의 다른 글

#6 Java Loops  (0) 2015.11.18
#5 Java Output Formatting  (0) 2015.11.17
#4 Java Stdin and Stdout 2  (0) 2015.11.17
#2 Java Stdin and Stdout 1  (0) 2015.11.17
#1 Welcome to Java!  (0) 2015.11.17

#2 Java Stdin and Stdout 1

HackerRank/HR-Java 2015. 11. 17. 00:06 by 후뤼한잉여

https://www.hackerrank.com/challenges/java-stdin-and-stdout-1


3번 입력받아 출력하는 문제


입력 예)

42
100
125


출력 예)

42
100
125


보낸 답)

import java.util.*;


public class Solution {


    public static void main(String[] args) {

      Scanner sc=new Scanner(System.in);

            

      for(int i=0; i<3; i++) {

        System.out.println(sc.nextInt());

      }

    }

}


'HackerRank > HR-Java' 카테고리의 다른 글

#6 Java Loops  (0) 2015.11.18
#5 Java Output Formatting  (0) 2015.11.17
#4 Java Stdin and Stdout 2  (0) 2015.11.17
#3 Java If-Else  (0) 2015.11.17
#1 Welcome to Java!  (0) 2015.11.17

#1 Welcome to Java!

HackerRank/HR-Java 2015. 11. 17. 00:03 by 후뤼한잉여

https://www.hackerrank.com/challenges/welcome-to-java


단순히 출력하는 문제


출력 예)

Hello World.
Hello Java.


보낸 답)

public class Solution {


   public static void main(String []argv) {

      System.out.println("Hello World.");

      System.out.println("Hello Java.");

   }


}


'HackerRank > HR-Java' 카테고리의 다른 글

#6 Java Loops  (0) 2015.11.18
#5 Java Output Formatting  (0) 2015.11.17
#4 Java Stdin and Stdout 2  (0) 2015.11.17
#3 Java If-Else  (0) 2015.11.17
#2 Java Stdin and Stdout 1  (0) 2015.11.17

도전!

HackerRank 2015. 11. 16. 23:59 by 후뤼한잉여

알고리즘 이나 프로그래밍 문제를 푸는 사이트 중 하나로 온라인 면접시 많이 사용한다는 해커랭크 라는 사이트에 적응해보기 위해 챌린지에 도전!

허접하지만 하루에 한개씩이라도 풀어보기로 했습니다.

어짜피 잉여니까요 ^^


https://www.hackerrank.com

Today :

Total : | Yesterday :

Recent Post
Recent Comment
Recent Trackback
Archive
Link