-
[Codewars] RGB To Hex ConversionAlgorithm 2021. 3. 23. 18:33
www.codewars.com/kata/513e08acc600c94f01000001/train/javascript
Codewars: Achieve mastery through challenge
Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.
www.codewars.com
더보기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풀이
- r, g, b 10진수를 16진수로 변환
- 10진수가 255이상이면 255으로, 0이하면 0으로
- 16진수로 변환한 값의 길이가 1이면 앞에 '0' 더해줌
- r, g, b 다 더하고 리턴
function rgb(r, g, b){ let result = ''; let hexR = r.toString(16).toUpperCase(); let hexG = g.toString(16).toUpperCase(); let hexB = b.toString(16).toUpperCase(); // 0 이하 if(r <= 0) hexR = '00'; if(g <= 0) hexG = '00'; if(b <= 0) hexB = '00'; // 255 이상 if(r >= 255) hexR = 'FF'; if(g >= 255) hexG = 'FF'; if(b >= 255) hexB = 'FF'; // 16진수 길이가 1 if(hexR.length === 1) hexR = '0' + hexR; if(hexG.length === 1) hexG = '0' + hexG; if(hexB.length === 1) hexB = '0' + hexB; result = hexR + hexG + hexB return result; }
다른 사람 풀이
function rgb(r, g, b){ return toHex(r)+toHex(g)+toHex(b); } function toHex(d) { if(d < 0 ) {return "00";} if(d > 255 ) {return "FF";} return ("0"+(Number(d).toString(16))).slice(-2).toUpperCase() }
'Algorithm' 카테고리의 다른 글
[프로그래머스] 기능개발 (0) 2021.03.30 [Codewars] Bit Counting (0) 2021.03.29 [Codewars] Dubstep (0) 2021.03.22 [Codewars] Array.diff (0) 2021.03.20 [프로그래머스] 소수 만들기 (0) 2021.03.18