#2059

Minimum Operations to Convert Number

specialist · 845 · lc medium +31 · verified · 51.6% accepted · 681 likes · top 41%

Description

Starting from x = start, repeatedly apply one of three operations using any element nums[i]: x + nums[i], x - nums[i], or x XOR nums[i]. Operations are only allowed while 0 <= x <= 1000, but a single operation may push x outside that range to reach goal directly. Return the fewest operations to reach goal, or -1 if impossible.

Example 1:

Input: nums = [2,4,12], start = 2, goal = 12
Output: 2
Explanation: We can go from 2 &rarr; 14 &rarr; 12 with the following 2 operations.
- 2 + 12 = 14
- 14 - 2 = 12

Example 2:

Input: nums = [3,5,7], start = 0, goal = -4
Output: 2
Explanation: We can go from 0 &rarr; 3 &rarr; -4 with the following 2 operations.
- 0 + 3 = 3
- 3 - 7 = -4
Note that the last operation sets x out of the range 0 <= x <= 1000, which is valid.

Example 3:

Input: nums = [2,8,16], start = 0, goal = 1
Output: -1
Explanation: There is no way to convert 0 into 1.

Code

1
2
3