nn00   3년 전

const [A, B] = input[0].split(" ").map(Number)

let answer = 1
let tempB = B

while(tempB !== A) {
  if (tempB % 10 === 1) {
    tempB = ~~(tempB / 10)
    answer += 1
  } else if (tempB % 2 === 0) {
    tempB /= 2
    answer += 1
  } else {
    answer = -1;
    break;
  }
}

if (tempB === A) {
  console.log(answer)
} else {
  console.log(-1)
}

해당 코드와 같이 while문 안에서 조건문을 통해 해결 하려는데 입력 예제가 3 8인 경우에는 무한 루프가 되더라구요.
(댓글로 알려주신 cina***님 감사합니다)

그래서 아래와 같이 조건을 추가하여 해결하였습니다!

const [A, B] = input[0].split(" ").map(Number)
let answer = 1
let tempB = B

while(tempB !== A && tempB !== 0) {
  if (tempB % 10 === 1) {
    tempB = ~~(tempB / 10)
    answer += 1
  } else if (tempB % 2 === 0) {
    tempB /= 2
    answer += 1
  } else {
    answer = -1;
    break;
  }
}

if (A > tempB) {
  console.log(-1)
} else {
  console.log(answer)
}

댓글을 작성하려면 로그인해야 합니다.