Javascript-625-Minimum Factorization——Tencent interview question bank

Problem index (maximum 5): ⭐

topic

Given a positive integer a, to find the smallest positive integer bsuch that bthe number of bits by multiplying all exactly equal a.

If there is no such result or the result is not a 32-bit signed integer, return 0.

Sample 1

Enter:

48 

Output:

68

Sample 2

Enter:

15

Output:

35

LeetCode original question guide

prompt:

"There is no such result" There is a case where the given integer contains a prime factor greater than 10, do not forget to judge

answer

We can start from the lowest digit (one digit) to enumerate the answers, try to put the digits on the small digits as large as possible.

So we start enumerating from the lowest bit and keep putting 9 until a cannot be divided by 9, that is, a can be expressed as a = a0 * 9 ^ t and t is as large as possible. Next, we keep putting 8 until a0 cannot be divisible by 8, keep putting 7 until a0 cannot be divisible by 7, and so on. This greedy method is essentially the same as the depth-first search strategy, except that the final answer is found directly, avoiding unnecessary searches.

Complexity analysis

Time complexity: O (log a), after factoring a number, it can be expressed at most as the product of O (log a) number.

Space complexity: O (1).

Javascript implementation

/**
 * @param {number} a
 * @return {number}
 */

var smallestFactorization = function (a) {
    result = [];
    // 10以下的直接返回本身
    if (a < 10) {
        return a;
    }
    // 太大舍弃
    else if (a > 2 ** 31) {
        return 0;
    }
    let k = 9;
    while (a > 1 && k > 1) {
        if (a % k === 0) {
            a = a / k;
            result.unshift(k);
            // k = 9; k不需要重置为9,因为每次都是贪心策略,大于当前k的值已经无法被a整除
            continue;
        }
        else {
            k--;
        }
    }
    result = Number(result.join(''));
    // 判断因式是否有大于10的质数
    if (result > 2 ** 31 || a >= 10) return 0;
    return result;
};
console.log(smallestFactorization(22));
console.log(smallestFactorization(15));

Experience

Recently in the front-end internship work, the js system learned a bit, and then decisively transfer python to js. js is still fragrant, all conversion functions are readily available.

Conversion function used:

The storage result is added from the head of the array in order starting from the single digit-unshift ()

Remove the comma between each element of the array and convert it to a string-join ()

Convert string to number-Number ()

Guess you like

Origin www.cnblogs.com/zhoujiayingvana/p/12681761.html