Description
You are given a positive integer n.
Return the maximum product of any two digits in n.
Note: You may use the same digit twice if it appears more than once in n.
Example 1:
Input: n = 31
Output: 3
Explanation:
- The digits of
nare[3, 1]. - The possible products of any two digits are:
3 * 1 = 3. - The maximum product is 3.
Example 2:
Input: n = 22
Output: 4
Explanation:
- The digits of
nare[2, 2]. - The possible products of any two digits are:
2 * 2 = 4. - The maximum product is 4.
Example 3:
Input: n = 124
Output: 8
Explanation:
- The digits of
nare[1, 2, 4]. - The possible products of any two digits are:
1 * 2 = 2,1 * 4 = 4,2 * 4 = 8. - The maximum product is 8.
Constraints:
10 <= n <= 109
Solutions
This function, maxProduct, finds the largest product of two digits in a number n by repeatedly extracting its last digit with n % 10 and stripping it off with n = Math.floor(n / 10). At each step, it first checks whether multiplying the current digit (rem) by the largest digit seen so far (max, correctly initialized to 0) beats the best product found so far (res), then updates max if the current digit is a new largest; by the time all digits are processed, res holds the maximum product of any two digits in the number.
/**
* @param {number} n
* @return {number}
*/
var maxProduct = function(n) {
let max = 0;
let res = 0;
while (n > 0) {
const rem = n % 10;
res = Math.max(res, rem * max);
max = Math.max(max, rem);
n = Math.floor(n / 10);
}
return res;
};