[04.19.22] Codewars

RGB To Hex Conversion

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

My answer

function rgb(r, g, b){
  let hexR = rgbToHex(r);
  let hexG = rgbToHex(g);
  let hexB = rgbToHex(b);

  return `${hexR}${hexG}${hexB}`;
}

function rgbToHex(num) {
  let a;
  if (num < 0) {
    a = '0';
  } else {
    if (num > 255) {
      a = 'FF';
    } else {
      a = num.toString(16).toUpperCase();
    }
  }
  return a.length === 1 ? `0${a}` : a;
}

Other solutions

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()
}
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);
  }).join('').toUpperCase();
}

Wrap up

Math.max(0, Math.min(255, x))

Returns a number whose value is limited to the given range(0~255).

Opposite number

Description

Very simple, given an integer or a floating-point number, find its opposite.
Examples:
1: -1
14: -14
-34: 34

My answer

function opposite(number) {
  return number*-1;
}

Other solutions

function opposite(number) {
  return(-number);
}
function opposite(number) {
  return number > 0 ? -number : Math.abs(number);
}

Find the odd int

Description

Given an array of integers, find the one that appears an odd number of times.
There will always be only one integer that appears an odd number of times.
Examples:
[7] should return 7, because it occurs 1 time (which is odd).
[0] should return 0, because it occurs 1 time (which is odd).
[1,1,2] should return 2, because it occurs 1 time (which is odd).
[0,1,0,1,0] should return 0, because it occurs 3 times (which is odd).
[1,2,2,3,3,3,4,3,3,3,2,2,1] should return 4, because it appears 1 time (which is odd).

My answer

function findOdd(A) {
  for(let i = 0; i < A.length; i++) {
    let filteredArray = A.filter(a => a === A[i]);
    if (filteredArray.length % 2 !== 0) {
      return A[i];
    }
  }
}

Other solutions

function findOdd(arr) {
  return arr.find((item, index) => arr.filter(el => el == item).length % 2)
}

좋은 웹페이지 즐겨찾기