关于二分法的编程题,求大佬指点

小赛于1
  • 3
新手上路,请多包涵

回复
阅读 367
2 个回答
✓ 已被采纳
function getNum(k){
    //  个位    十位      百位
    // 9 * 1 + 90 * 2 + 900 * 3 + ...
    let b = 0, start, end = 0
    do{
        start = end
        end += 9 * (10 ** b) * (b + 1)
        b++
    }while(k > end)

    let num = Math.ceil((k - start) / b) + 10 ** (b - 1) - 1
    let index = (k - start - 1) % b
    console.log(num, index)
    return String(num)[index]
}
function nth1(n) {
  let s = "";
  let c = 1;
  while (1) {
    s += c++;
    if (s.length >= n) return s[n - 1];
  }
}

function nth2(n) {
  const nine = 9;
  let sum = 0;
  let dist = 0;
  let len = 0;
  while (1) {
    sum += nine * len;
    dist += nine;
    if (sum >= n) {
      sum -= nine * len;
      dist -= nine;
      n -= sum;
      break;
    }
    nine *= 10;
    len++;
  }
  const diff = Math.ceil(n / len);
  const d = n % len || len;
  return (dist + diff + "").charAt(d - 1);
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏