Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Giảm số về 1 với tối thiểu phép toán trong JavaScript


Vấn đề

Cần viết hàm JS nhận số num. Cho phép 2 phép toán: nếu chẵn -> num/2; nếu lẻ -> num+1 hoặc num-1. Tìm số phép toán tối thiểu để đưa num về 1.

Ví dụ:

const num = 7;

Kết quả:

const output = 4;

Giải thích:

7 -> 8 -> 4 -> 2 -> 1 hoặc 7 -> 6 -> 3 -> 2 -> 1 (4 bước).

Ví dụ

Mã thực hiện:

const num = 7; const downToOne = (num = 1) => {    let min = Number.POSITIVE_INFINITY;    let stack = [{ num: num, step: 0 }];    let set = new Set();    let next;    let item;    while (stack.length) {       item = stack.shift();       if (item.num === 1) {          if (min > item.step) {             min = item.step;          }          continue;       }       if (set.has(item.num) || item.step >= min) {          continue;       }       set.add(item.num);       next = item.step + 1;       if (item.num % 2 === 0) {          item.num /= 2;          stack.push({ num: item.num, step: next });       } else {          stack.push({ num: item.num - 1, step: next });          stack.push({ num: item.num + 1, step: next });       }    }    return min; }; console.log(downToOne(num));

Kết quả

Kết quả in ra console:

4