codewars--js--RGB To Hex Conversion
2024-09-06 19:31:14
问题描述:
The rgb() method is incomplete. Complete the method so that passing in RGB decimal values will result in a hexadecimal representation being returned. The valid decimal values for RGB are 0 - 255. Any (r,g,b) argument values that fall out of that range should be rounded to the closest valid value.
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
我的思路:
这道题做法很简单,主要就是通过toString(n)将10进制转换成16进制(注意,n的取值范围是2~36)。但是自己的写法就比较直接,很是繁琐,看到大神们的写法真是简洁。尤其是slice、map用法,拍案叫绝。
我的答案:
function rgb(r, g, b){
// complete this function
r=a(r);g=a(g);b=a(b);
r=r.toString(16).toUpperCase();
g=g.toString(16).toUpperCase();
b=b.toString(16).toUpperCase();
var c=r.concat(g).concat(b);
if(c=="000"){return "000000";}
else{return c;}
}
function a(n){
if(n>255){return n=255;}
if(n<0){return n=0;}
if(n>=0 && n<=255){return n;}
}
优秀答案:
(1)
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() //slice(-2)作用若为0,则返回00;若为255,则返回ff
}
(2)
function rgb(r, g, b){
return [r,g,b].map(function(x) {
return ('0'+Math.max(0, Math.min(255, x)).toString(16)).slice(-2); //将<0或>255的分别置为0或255.
}).join('').toUpperCase();
}
哈哈哈!
最新文章
- ubuntu安装ANSYS17.2全过程
- BZOJ 3771: Triple
- *HDU1846HDU2188 巴什博奕
- AngularJs $q promise
- 《Javascript设计模式》笔记一js的表现力
- MSDN Kinect for Windows SDK中文版论坛开放了
- [Linux] 取得服务器版本
- Android 身份证号码查询、手机号码查询、天气查询
- qemu-kvm命令
- Web APP 随笔
- c# xml操作类
- 用ifconfig命令,只有lo,没有eth0的解决方案
- 4)Javascript设计模式:Decorator模式
- android 屏幕适配,hdpi,xhdpi,xxhdpi理解,常见出图
- MySQL 上手教程
- 网页发起qq临时会话
- mac 修改root密码
- Switch 中参数的范围探讨
- Apollo 启动脚本解析
- [转] AForge.NET 图像处理类