본문으로 건너뛰기

"hackerrank" 태그로 연결된 20개 게시물개의 게시물이 있습니다.

모든 태그 보기

· 약 2분
karais89

문제 요약

일반 시간을 군대 시간으로 변경하기.

Sample Input

07:05:45PM

Sample Output

19:05:45

내 소스

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

static string timeConversion(string s) {
// Complete this function
string time = s.Substring(0, 8);
string timeFormat = s.Substring(8);

string[] timeSplit = time.Split(':');
int hour = 0;
if (timeFormat == "PM")
{
hour = Convert.ToInt32(timeSplit[0]) + 12;
if (hour == 24)
{
hour = 12;
}
}
else
{
hour = Convert.ToInt32(timeSplit[0]);
if (hour == 12)
{
hour = 0;
}
}
return string.Format("{0:00}:{1:00}:{2:00}", hour, timeSplit[1], timeSplit[2]);
}

static void Main(String[] args) {
string s = Console.ReadLine();
string result = timeConversion(s);
Console.WriteLine(result);
}
}

vatsalchanana의 답안

#include<iostream>
#include<cstdio>

using namespace std;

int main() {
string s;
cin >> s;

int n = s.length();
int hh, mm, ss;
hh = (s[0] - '0') * 10 + (s[1] - '0');
mm = (s[3] - '0') * 10 + (s[4] - '0');
ss = (s[6] - '0') * 10 + (s[7] - '0');

if (hh < 12 && s[8] == 'P') hh += 12;
if (hh == 12 && s[8] == 'A') hh = 0;

printf("%02d:%02d:%02d\n", hh, mm, ss);

return 0;
}

Jashin의 답안

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);
String time = scan.next();
String tArr[] = time.split(":");
String AmPm = tArr[2].substring(2,4);
int hh,mm,ss;
hh = Integer.parseInt(tArr[0]);
mm = Integer.parseInt(tArr[1]);
ss = Integer.parseInt(tArr[2].substring(0,2));

String checkPM = "PM",checkAM ="AM";
int h = hh;
if(AmPm.equals(checkAM) && hh==12)
h=0;
else if(AmPm.equals(checkPM)&& hh<12)
h+=12;

System.out.printf("%02d:%02d:%02d",h,mm,ss);
}

느낀점

AM, PM을 군대 시간으로 바꾸는 문제이다.

· 약 3분
karais89

문제 요약

첫번째 인수로는 양초의 개수를 받고

나머지 인수는 그 양초의 높이를 각각 받는다.

콜린은 양초의 높이가 가장 큰 것들만 불을 끌 수 있다.

그녀가 성공적으로 날려버릴 수 있는 양초를 출력해라.

Sample Input

4
3 2 1 3

Sample Output

2

내 소스

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

static int birthdayCakeCandles(int n, int[] ar) {
// Complete this function
int max = ar[0];
int maxCount = 0;

for (int i = 0; i < n; i++)
{
if (max < ar[i])
{
max = ar[i];
}
}

for (int i = 0; i < n; i++)
{
if (ar[i] == max)
{
maxCount++;
}
}

return maxCount;
}

static void Main(String[] args) {
int n = Convert.ToInt32(Console.ReadLine());
string[] ar_temp = Console.ReadLine().Split(' ');
int[] ar = Array.ConvertAll(ar_temp,Int32.Parse);
int result = birthdayCakeCandles(n, ar);
Console.WriteLine(result);
}
}

shashank21j의 답안

자바의 경우는 나와 거의 같은 식으로 풀었다.

import java.util.*;

public class Solution {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);

// the number of candles
int n = scan.nextInt();

// store the current maximum height of any candle, initialize to the minimum possible height of any candle
int maxHeight = 1;

// count the number of candles having the maximum height
int countMax = 0;

for(int i = 0; i < n; i++) {
int tmp = scan.nextInt();

// if you read in a value larger than maxHeight, set new maxHeight
if(tmp > maxHeight) {
maxHeight = tmp;
countMax = 1;
}
// if you read a value equal to the current value of maxHeight
else if(tmp == maxHeight) {
// increment the count of candles having maximum height
countMax++;
}
}
scan.close();

System.out.println(countMax);
}
}

파이썬의 경우는 3줄로 표현이 가능하다.

n = input()
arr = map(int, raw_input().split())
print arr.count(max(arr))

느낀점

문제 자체는 그냥 주어진 배열의 맥스값을 구하고, 맥스값의 개수를 구하는 문제이다.

· 약 2분
karais89

문제 요약

5개의 정수가 주어지고 그 중에 4개를 선택할때 나올 수 있는 최소값과 최대값을 구해라.

Sample Input

1 2 3 4 5

Sample Output

10 14

내 소스

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

static void Main(String[] args) {
string[] arr_temp = Console.ReadLine().Split(' ');
int[] arr = Array.ConvertAll(arr_temp,Int32.Parse);

int min = arr[0];
int max = arr[0];
long sum = 0;
for (int i = 0; i < arr.Length; i++)
{
if (min > arr[i])
{
min = arr[i];
}

if (max < arr[i])
{
max = arr[i];
}

sum += arr[i];
}

Console.Write("{0} {1}", sum-max, sum-min);
}
}

느낀점

문제 자체는 5개 중에 4개를 선택해서 나올 수 있는 최소값과 최대값을 구하는 것이다.

하지만 이걸 다른식으로 생각하면 5개 중에 가장 큰 수를 선택해서 뺀 값이 최소값 5개 중에 가장 작은 값을 구해서 뺀 값이 최대값이다.

· 약 2분
karais89

문제 요약

계단 문제.

n을 입력받으면 그 n만큼의 계단모양의 #을 출력해라.

Sample Input

6 

Sample Output

     #
##
###
####
#####
######

내 소스

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

static void Main(String[] args) {
int n = Convert.ToInt32(Console.ReadLine());

for (int i = 0; i < n; i++)
{
// space
for (int j = n-i-1; j > 0; j--)
{
Console.Write(' ');
}

// #
for (int k = 0; k < i+1; k++)
{
Console.Write('#');
}

// new line
Console.WriteLine();
}
}
}

vatsalchanana의 답안

#include<iostream>

using namespace std;

int main () {
int height;
cin >> height;

for (int i = 1; i <= height; i++) {
for (int j = 0; j < i; j++) {
if(j==0) {
//Printing spaces
for(int t = 0; t < height - i; t++) cout << " ";
}
//Print hashes
cout << "#";
}
cout << endl;
}
return 0;
}

svecon 답안

이런식으로 한줄로 표현할 수도 있다.

using System;
class Solution
{
static void Main(String[] args)
{
int N = int.Parse(Console.ReadLine());
for (int i = 0; i < N; i++)
Console.WriteLine(new String('#', i + 1).PadLeft(N, ' '));
}
}

느낀점

학부 시간에 c를 배울때 하는 * 출력하는 문제랑 똑같은 문제.

· 약 2분
karais89

문제 요약

첫번째 인풋은 입력받을 정수의 개수 나머지 인풋은 그 정수의 값들을 받는다.

3개의 라인으로 출력해라.

  1. 양수의 개수 / 정수의 개수
  2. 음수의 개수 / 정수의 개수
  3. 0의 개수 / 정수의 개수

소수 6째 자리까지 표현 해야된다.

Sample Input

6
-4 3 -9 0 4 1
  • 양수 : 3개(3,4,1)
  • 음수 : 2개(-4,-9)
  • 0 : 1개(0)

Sample OutPut

0.500000
0.333333
0.166667
  1. 3/6 = 0.500000
  2. 2/6 = 0.333333
  3. 1/6 = 0.166667

내 소스

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

static void Main(String[] args) {
int n = Convert.ToInt32(Console.ReadLine());
string[] arr_temp = Console.ReadLine().Split(' ');
int[] arr = Array.ConvertAll(arr_temp,Int32.Parse);

int plusCount = 0;
int minusCount = 0;
int zeroCount = 0;

for (int i = 0; i < n ; i++)
{
if (arr[i] > 0)
plusCount++;
else if (arr[i] < 0)
minusCount++;
else
zeroCount++;
}

Console.WriteLine(string.Format("{0:f6}", (float)plusCount/n));
Console.WriteLine(string.Format("{0:f6}", (float)minusCount/n));
Console.WriteLine(string.Format("{0:f6}", (float)zeroCount/n));
}
}

vatsalchanana의 답안

#include<iostream>

using namespace std;

int main() {
int n;
cin >> n;

float pl = 0, mn = 0, zr = 0;

for (int i = 0; i < n; i++) {
int val;
cin >> val;
zr += (val == 0);
pl += (val > 0);
mn += (val < 0);
}

zr = zr / (double)n;
pl = pl / (double)n;
mn = mn / (double)n;

printf("%0.06lf\n%0.06lf\n%0.06lf\n", pl, mn, zr);
return 0;
}

느낀점

문제 자체는 크게 어려운게 없다.

콘솔 출력시 서식문자를 가지고 출력하는 방법만 알면 쉬운 문제다.

· 약 3분
karais89

문제 요약

첫번째 input은 N x N 배열을 만들어 줄때 필요한 N의 개수

그리고 나머지 input은 그 배열의 각각의 인수의 값.

배열의 첫번째 대각선의 합(왼쪽 상단에서 시작해서 오른쪽 하단으로 끝나는)과 두번째 대각선(오른쪽 상단에서 시작해서 왼쪽 하단으로 끝나는)의 차를 절대값을 구하는 문제.

ex)

3
11 2 4
4 5 6
10 8 -12
  • 첫번째 대각선의 합 : 11 + 5 - 12 = 4
  • 두번째 대각선의 합 : 4 + 5 + 10 = 19
  • 두 대각선의 차이의 절대값 : |4 - 19| = 15

내 소스

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

static void Main(String[] args) {
int n = Convert.ToInt32(Console.ReadLine());
int[][] a = new int[n][];
for(int a_i = 0; a_i < n; a_i++){
string[] a_temp = Console.ReadLine().Split(' ');
a[a_i] = Array.ConvertAll(a_temp,Int32.Parse);
}

// primary diagonal (0,0), (1,1), (2,2)
int primarySum = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i == j)
primarySum += a[i][j];
}
}

// secondary diagonal (2,0) (1,1) (0,2)
int secondarySum = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i+j == n-1)
secondarySum += a[i][j];
}
}

int diff = primarySum - secondarySum;
Console.Write(Math.Abs(diff));
}
}

vatsalchanana의 답안

#include <iostream>

using namespace std;

int main() {
int n;
cin >> n;

int arr[n][n];

long long int d1=0; //First Diagonal
long long int d2=0; //Second Diagonal

for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> arr[i][j];
if (i == j) d1 += arr[i][j];
if (i == n - j - 1) d2 += arr[i][j];
}
}

cout << abs(d1 - d2) << endl; //Absolute difference of the sums across the diagonals
return 0;
}

느낀점

배열에서 첫 번째 대각선과 두번째 대각선의 인덱스 값을 구하는 방법을 생각하면 풀 수 있는 문제.

나의 경우에는 첫번째 대각선과 두번째 대각선을 각각 for문으로 돌려서 푸는 방식을 택하였다.

vatsalchanana의 경우는 for문 하나에서 대각선의 합을 구해버리는 방식으로 문제를 해결 하였다.

· 약 2분
karais89

문제 요약

첫 번째 인수는 배열의 인자 개수. 두번째 인자는 배열을 인자로 받는다.

배열의 크기의 합을 구하는 문제이다. 배열의 합은 매우 크므로 c/c++은 long long 자료형을 사용하고,

자바의 경우 long 자료형을 사용해서 배열의 합을 구하자.

내 소스

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

static long aVeryBigSum(int n, long[] ar) {
// Complete this function
long sum = 0;
for (int i = 0; i < n ; i++)
{
sum += ar[i];
}
return sum;
}

static void Main(String[] args) {
int n = Convert.ToInt32(Console.ReadLine());
string[] ar_temp = Console.ReadLine().Split(' ');
long[] ar = Array.ConvertAll(ar_temp,Int64.Parse);
long result = aVeryBigSum(n, ar);
Console.WriteLine(result);
}
}

느낀점

배열의 합을 구하면 된다.

배열의 합은 매우 크므로 long 자료형을 사용해서 구해주면 끝..

HackerRank Warup 2번째 문제와 같은 방식으로 구했다.

· 약 2분
karais89

문제 요약

두개의 배열에서

A = (a0, a1, a2)

B = (b0, b1, b2)

a0 > b0 이면 a가 1점을 얻음

a0 == b0 이면 아무도 점수를 얻지 못함

a0 < b0 이면 b가 1점을 얻음

a와 b가 얻은 총 점수를 순서대로 출력 하는 문제

내 소스

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

static int[] solve(int a0, int a1, int a2, int b0, int b1, int b2){
// Complete this function
int sumA = 0;
int sumB = 0;

int[] arrA = new int[] { a0, a1, a2 };
int[] arrB = new int[] { b0, b1, b2 };

for (int i = 0; i < arrA.Length; i++)
{
if (arrA[i] > arrB[i])
sumA += 1;
else if (arrA[i] < arrB[i])
sumB += 1;
}
return new int[] { sumA, sumB };
}

static void Main(String[] args) {
string[] tokens_a0 = Console.ReadLine().Split(' ');
int a0 = Convert.ToInt32(tokens_a0[0]);
int a1 = Convert.ToInt32(tokens_a0[1]);
int a2 = Convert.ToInt32(tokens_a0[2]);
string[] tokens_b0 = Console.ReadLine().Split(' ');
int b0 = Convert.ToInt32(tokens_b0[0]);
int b1 = Convert.ToInt32(tokens_b0[1]);
int b2 = Convert.ToInt32(tokens_b0[2]);
int[] result = solve(a0, a1, a2, b0, b1, b2);
Console.WriteLine(String.Join(" ", result));
}
}

느낀점

배열의 값을 비교하고 그 값을 변수에 각각 저장해 주면 된다.

· 약 1분
karais89

문제 요약

첫 번째 인수에는 배열의 크기가, 두번째 인수에는 배열이 들어온다. 배열의 합을 구해라.

내 소스

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

static int simpleArraySum(int n, int[] ar) {
// Complete this function
int sum = 0;
for (int i = 0; i < n; i++)
{
sum += ar[i];
}
return sum;
}

static void Main(String[] args) {
int n = Convert.ToInt32(Console.ReadLine());
string[] ar_temp = Console.ReadLine().Split(' ');
int[] ar = Array.ConvertAll(ar_temp,Int32.Parse);
int result = simpleArraySum(n, ar);
Console.WriteLine(result);
}
}

느낀점

워밍업 단계.

가장 기초적인 배열의 합 구하는 문제.

배열의 크기를 첫번째 인자로 넘겨주는 이유는 C언어 같은 언어는 배열의 크기를 알 수 없기 때문인 것 같다.

· 약 1분
karais89

문제 요약

stdin으로 읽은 두 정수의 합을 반환하는 함수를 만들어라.

내 소스

using System;
using System.Collections.Generic;
using System.IO;
class Solution {
static int solveMeFirst(int a, int b) {
// Hint: Type return a+b; below
return a + b;
}
static void Main(String[] args) {
int val1 = Convert.ToInt32(Console.ReadLine());
int val2 = Convert.ToInt32(Console.ReadLine());
int sum = solveMeFirst(val1,val2);
Console.WriteLine(sum);
}
}

느낀점

워밍업 단계라 주석에 이미 답이 나와 있다.

익숙한 C#으로 작성했다.

테스트 케이스가 작성되어 테스트 통과 후 답을 제출하면 된다.