算法示例

1.调换正整数两个数值的位置,得到一个最大的数

// 正整数:调换正整数两个数值的位置,得到一个最大的数

// 入参:num
// 返回值:最大数
function swapToGetMax(number) {
  // 将整数转换为字符串以便于处理
  let numStr = number.toString();
  let max = -1; // 初始化最大值为-1

  // 遍历每一对数字,尝试交换它们,然后比较是否获得了更大的值
  for (let i = 0; i < numStr.length - 1; i++) {
    for (let j = i + 1; j < numStr.length; j++) {
      // 交换数字位置
      let swapped = numStr.slice(0, i) + numStr[j] + numStr.slice(i + 1, j) + numStr[i] + numStr.slice(j + 1);

      // 将字符串转换回整数,然后比较是否更大
      let swappedNumber = parseInt(swapped);
      if (swappedNumber > max) {
        max = swappedNumber;
      }
    }
  }

  console.log(`原始数: ${number}`);
  console.log(`交换后获得的最大数: ${max}`);
  return max;
}

console.log(swapToGetMax(12348963));

// 结果:
// 原始数: 12348963
// 交换后获得的最大数: 92348163

2.十六进制的颜色转十进制的 rgb:

// 输入一个16进制的颜色,转化为10进制的rgb:
// 支持 三位16进制的颜色:
// 例如:"#FF0000"转化为"rgb(255,255,0)"
// 例如:"#F00"转化为"rgb(255,255,0)"

function colorHexToRgb(hexColor) {
  if (!hexColor || typeof hexColor !== 'string') {
    return hexColor;
  }

  const match = hexColor.toLowerCase().match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/);
  if (!match) {
    return hexColor;
  }

  const hexStr = match[1];
  let rStr, gStr, bStr;
  if (hexStr.length === 3) {
    rStr = hexStr.slice(0, 1) + hexStr.slice(0, 1)
    gStr = hexStr.slice(1, 2) + hexStr.slice(1, 2)
    bStr = hexStr.slice(2) + hexStr.slice(2)
  } else {
    rStr = hexStr.slice(0, 2)
    gStr = hexStr.slice(2, 4)
    bStr = hexStr.slice(4)
  }
  const rgb = [rStr, gStr, bStr].map(hexToDecimal).join()
  // 或者直接通过parseInt()转16进制:
  // const rgb = [rStr, gStr, bStr].map((str => parseInt(str, 16))).join()
  return `rgb(${rgb})`

}

function hexToDecimal(hex) {

  const hexTotalStr = "0123456789abcdef";
  let total = 0;
  const decicalStr = hex.split('').reverse().forEach((str, index) => {
    total += hexTotalStr.indexOf(str) * Math.pow(16, index)
  })
  return total;
}

console.log(colorHexToRgb("#FF0001"))  //rgb(255,0,1)
console.log(colorHexToRgb("#abc"))     //rgb(170,187,204)
console.log(colorHexToRgb("#002233"))  //rgb(0,34,51)
Contributors: masecho