본문 바로가기
알고리즘/Codewars

[Codewars] RGB To Hex Conversion (5 kyu) / JavaScript

by fluss 2022. 10. 20.

https://www.codewars.com/kata/513e08acc600c94f01000001

 

Codewars - Achieve mastery through coding practice and developer mentorship

Coding practice for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

The rgb function is incomplete. Complete it so that passing in RGB decimal values will result in a hexadecimal representation being returned. Valid decimal values for RGB are 0 - 255. Any values that fall out of that range must be rounded to the closest valid value.

Note: Your answer should always be 6 characters long, the shorthand with 3 will not work here.

The following are examples of expected output values:

rgb(255, 255, 255) // returns FFFFFF
rgb(255, 255, 300) // returns FFFFFF
rgb(0,0,0) // returns 000000
rgb(148, 0, 211) // returns 9400D3

 

설명:

rgb 함수는 불완전합니다. RGB 십진법 값을 전달받아 16진법 표현으로 반환하는 결과를 나타내도록 완성하세요. RGB의 유효한 10진법 값은 0 - 255입니다. 범위를 벗어난 모든 값은 대략 가장 가까운 유효한 값이 되어야 합니다. 

참고: 답은 항상 6글자여야 하고 3글자 약어는 작동되지 않습니다.

예상되는 출력값은 다음과 같습니다:

rgb(255, 255, 255) // returns FFFFFF
rgb(255, 255, 300) // returns FFFFFF
rgb(0,0,0) // returns 000000
rgb(148, 0, 211) // returns 9400D3
 

 

풀이

function rgb(r, g, b){
  return toHex(r) + toHex(g) + toHex(b);
}

function toHex(n){
  if(n < 0) n = 0;
  else if(n > 255) n = 255;
  return n.toString(16).padStart(2, '0').toUpperCase();
}

toHex 함수를 따로 만들어 만약 들어오는 값 n이 0보다 작으면 n을 0으로 255보다 크면 n을 255로 만들어준다. 그리고 n을 16진법으로 바꾸고 padStart로 한자리 수인 경우 앞을 0으로 채워준다. 그리고 대문자로 바꿔주고 그 값을 반환한다. 이 함수에 r, g, b를 각각 넣고 실행한 결과를 합쳐서 반환했다.

댓글