[LeetCode] Least Operators to Express Number

964. Least Operators to Express Number

Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x … where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, , or /). For example, with x = 3, we might write 3 3 / 3 + 3 - 3 which is a value of 3.

When writing such an expression, we adhere to the following conventions:

  • The division operator (/) returns rational numbers.
  • There are no parentheses placed anywhere.
  • We use the usual order of operations: multiplication and division happen before addition and subtraction.
  • It is not allowed to use the unary negation operator (-). For example, “x - x” is a valid expression as it only uses subtraction, but “-x + x” is not because it uses negation.

We would like to write an expression with the least number of operators such that the expression equals the given target. Return the least number of operators used.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
unordered_map<long long, long long> dp;

int intlog(double base, double x) {
return (int)(log(x) / log(base));
}

public:
long long leastOpsExpressTarget(long long x, long long target) {
if(dp.count(target)) return dp[target];
long long& res = dp[target] = INT_MAX;

if(x == target) return res = 0;
if(x > target) return res = min(target * 2 - 1, (x - target) * 2);

int n = intlog(x, target);
if(pow(x, n) == target) return res = n - 1;

if(pow(x, n + 1) - target < target)
res = min(res, n + 1 + leastOpsExpressTarget(x, pow(x,n + 1) - target));
res = min(res, n + leastOpsExpressTarget(x, target - pow(x, n)));

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/31/PS/LeetCode/least-operators-to-express-number/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.