RGB To Hex Conversion

题目

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:

1
2
3
4
rgb(255, 255, 255) // returns FFFFFF
rgb(255, 255, 300) // returns FFFFFF
rgb(0,0,0) // returns 000000
rgb(148, 0, 211) // returns 9400D3

思路

需要注意的有以下几点

  • 数值小于0和大于255的情况
  • 数值小于16的时候转换出来的前面要加一个0

答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function rgb(r, g, b){
function hexit(n){
if(n<0){
return "00";
}else if(n>255){
return "FF";
}else if(n>=0&&n<16){
return "0"+n.toString(16);
}else{
return n.toString(16);
}
}
return (hexit(r)+hexit(g)+hexit(b)).toUpperCase();
}