Class Solution
- java.lang.Object
-
- g2001_2100.s2059_minimum_operations_to_convert_number.Solution
-
public class Solution extends Object
2059 - Minimum Operations to Convert Number.Medium
You are given a 0-indexed integer array
numscontaining distinct numbers, an integerstart, and an integergoal. There is an integerxthat is initially set tostart, and you want to perform operations onxsuch that it is converted togoal. You can perform the following operation repeatedly on the numberx:If
0 <= x <= 1000, then for any indexiin the array (0 <= i < nums.length), you can setxto any of the following:x + nums[i]x - nums[i]x ^ nums[i](bitwise-XOR)
Note that you can use each
nums[i]any number of times in any order. Operations that setxto be out of the range0 <= x <= 1000are valid, but no more operations can be done afterward.Return the minimum number of operations needed to convert
x = startintogoal, and-1if it is not possible.Example 1:
Input: nums = [2,4,12], start = 2, goal = 12
Output: 2
Explanation: We can go from 2 \u2192 14 \u2192 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 \u2192 3 \u2192 -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.
Constraints:
1 <= nums.length <= 1000-109 <= nums[i], goal <= 1090 <= start <= 1000start != goal- All the integers in
numsare distinct.
-
-
Constructor Summary
Constructors Constructor Description Solution()
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description intminimumOperations(int[] nums, int start, int goal)
-