본문 바로가기

Java Script/알고리즘 풀이

[알고리즘] 0827

문제 - Codewars_Keep Hydrated! (8kyu)

Nathan loves cycling. Because Nathan knows it is important to stay hydrated, he drinks 0.5 litres of water per hour of cycling.You get given the time in hours and you need to return the number of litres Nathan will drink, rounded to the smallest value.

For example:
time = 3 ----> litres = 1
time = 6.7---> litres = 3
time = 11.8--> litres = 5

문제 풀이

function litres(time) {
  return parseInt(time*0.5);
}
  1. time에 0.5를 곱한 수의 정수를 반환하면 Nathan이 마신 리터를 구할 수 있기 때문에 parseInt 함수를 이용해서 정수를 반환할 수 있도록 코드를 작성했다.

코드 비교

function litres(time) {
  return Math.floor(time * 0.5);
}
  1. 내가 푼 방식과 비슷하게 time에 0.5를 곱하고 Math.floor()메소드를 이용해서 소수점 이하의 숫자를 버림하고 정수를 반환하도록 코드가 작성되었다.
  2. (참고) 정수를 반환하는 메소드들
  • Math.floor() : 소수점 이하를 버림한다.
  • Math.ceil() : 소수점 이하를 올림한다.
  • Math.round() : 소수점 이하를 반올림한다.

문제 - Codewars_Abbreviate a Two Word Name (8kyu)

Write a function to convert a name into initials.
This kata strictly takes two words with one space in between them.
The output should be two capital letters with a dot separating them.

It should look like this:
Sam Harris => S.H
patrick feeney => P.F

문제 풀이

function abbrevName(name){
  let lastName = name.substr(0,1);
  let blankIndex = name.indexOf(" ")+1;
  let firstName = name.substr(blankIndex,1);
  
  return `${lastName.toUpperCase()}.${firstName.toUpperCase()}`
}
  1. 제공되는 이름의 가장 첫 번째 알파벳을 담을 lastName 변수 선언
  2. blankIndex 변수를 통해 공백의 인덱스 위치를 반환하는 함수에 + 1을 해서 공백 이후 알파벳의 인덱스를 확인할 수 있도록 코드 작성
  3. blankIndex를 이용해서 제공되는 성의 가장 첫 번째 알파벳을 담을 fisrtName 변수 선언
  4. 이후 return 문을 이용해서 반환값을 반환하도록 코드 작성

'Java Script > 알고리즘 풀이' 카테고리의 다른 글

[알고리즘] 0829  (0) 2023.08.29
[알고리즘] 0828  (0) 2023.08.28
[알고리즘] 0826  (0) 2023.08.26
[알고리즘] 0825  (0) 2023.08.25
[알고리즘] 0824  (0) 2023.08.24