zoukankan      html  css  js  c++  java
  • codewars--js--RGB To Hex Conversion

    问题描述:

    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();
    }

    哈哈哈!

  • 相关阅读:
    Kafka单机环境部署
    kafka启动出现:Unsupported major.minor version 52.0 错误
    CentOs7.3 搭建 Redis-4.0.1 Cluster 集群服务
    Python ZKPython 安装
    zookeeper伪集群安装
    系统吞吐量(TPS)、用户并发量、性能测试概念和公式
    XDebug安装配置教程
    48 条高效率的 PHP 优化写法
    待处理bug
    phpstudy composer 使用安装
  • 原文地址:https://www.cnblogs.com/hiluna/p/8880356.html
Copyright © 2011-2022 走看看