본문 바로가기

■ 프로그래밍/알고리즘

[JS] Human Readable Time

www.codewars.com/kata/52685f7382004e774f0001f7/train/javascript

 

[ 문제 ]

Write a function, which takes a non-negative integer (seconds) as input and returns the time in a human-readable format (HH:MM:SS)

  • HH = hours, padded to 2 digits, range: 00 - 99
  • MM = minutes, padded to 2 digits, range: 00 - 59
  • SS = seconds, padded to 2 digits, range: 00 - 59

The maximum time never exceeds 359999 (99:59:59)

You can find some examples in the test fixtures.

 

 

[ 풀이 ]

2020.11.15 (40min)

function humanReadable(seconds) {
  let hour = null;
  let min = null;
  let second = null;
  
  // 계산
  if (seconds < 60) {
    second = seconds;
  } else if (seconds < 3599) {
    min = parseInt(seconds / 60);
    second = seconds % 60;
  } else {
    hour = parseInt(seconds / 3600);
    const remain = seconds % 3600;
    min = parseInt(remain / 60);
    second = remain % 60;
  }
  
  // null이거나 10보다 작을 때 조건
  if (second === null) {
    second = '00'
  } else if (second < 10) {
    second = '0' + second
  }
  if (min === null) { 
    min = '00'
  } else if (min < 10) {
    min = '0' + min
  }
  if (hour === null) {
    hour = '00'
  } else if (hour < 10) {
    hour = '0' + hour
  }
  
  return `${hour}:${min}:${second}`
}

 

 

'■ 프로그래밍 > 알고리즘' 카테고리의 다른 글

JS 100제 - 1권 (Q1~)  (0) 2020.12.11
[JS] Format a string of names like 'Bart, Lisa & Maggie'.  (0) 2020.11.21
[JS] Vowel Count  (0) 2020.11.14
[JS] Stop gninnipS My sdroW!  (0) 2020.11.13
[JS] Regex validate PIN code  (0) 2020.11.12