刷题跟憨憨豆包吵起来

178 阅读1分钟

2.计算从位置 x 到 y 的最少步数 最多说我投机取巧,应该没错吧,差点跟豆包吵起来

function solution(xPosition, yPosition) {
  // Please write your code here
  let distance = Math.abs(xPosition-yPosition);  // 距离
  if(distance==0) return 0;
  // 找最大步数
  if(Math.sqrt(distance)==Math.floor(Math.sqrt(distance))){
    // 顶点对称
    // 距离刚好是某个数n的平方,则步数等于n*2-1 -> 1,2,3...n,n-1,n-2,...1
    return Math.sqrt(distance)*2-1;
  } else{
    // 否则向下取整平方根n为最大步数
    var n = Math.floor(Math.sqrt(distance));
    // 找规律,两个顶点对称之间有个两边对称,
    // 比如距离为6就是两边对称,步子就是1221,在4和9之间,小于6,步数和6相同,大于6,步数和9相同
    if( (n+1)*2 < distance){
      // 步数等于n*2+1  -> 1,2,3...n,n,n-1,n-2...1中间插入剩余步数
      return n*2+1;
    }
    else{
      // 步数等于n*2  -> 1,2,3...n,n-1,n-2...1中间插入剩余步数
      return n*2;
    }
  }
}

image.png