problem:
Difficulty: medium
Description:
Give the number X, then change X to Y, where X operates:
X can be multiplied by 2
X can be subtracted by 1.
Title link: https://leetcode.com/problems/broken-calculator/
Input range:
1 <= X <= 10^9
1 <= Y <= 10^9
Enter the case:
Example 1:
Input: X = 2, Y = 3
Output: 2
Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.
Example 2:
Input: X = 5, Y = 8
Output: 2
Explanation: Use decrement and then double {5 -> 4 -> 8}.
Example 3:
Input: X = 3, Y = 10
Output: 3
Explanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}.
Example 4:
Input: X = 1024, Y = 1
Output: 1023
Explanation: Use decrement operations 1023 times.
My code:
In fact, it is not difficult, but you need to think backwards, otherwise it will be overtime if you use dfs. If you change X to Y in the forward direction, you will be faced with the choice of * 2 or -1, and dfs is not suitable.
So the reverse thinking is that Y becomes X, and then the rules are reversed
Y can be divided by 2, only when Y is even and Y> X
Y can be + 1; this way it is easy to solve.
If X becomes Y, it’s really not clear* 2 is suitable or not, but on the other hand, Y / 2 is very clear
Java:
class Solution {
public int brokenCalc(int X, int Y) {
int opt = 0;
for(; X != Y; opt ++) {
if(Y > X && (Y & 1) == 0) Y >>= 1; // 如果是偶数先除以2为快
else if(Y > X) Y ++; // 如果奇数且 > X,加一
else return opt + X - Y; // 如果已经小于 X ,剩下也只有加一操作
}
return opt;
}
}
C++ (actually the same):
class Solution {
public:
int brokenCalc(int X, int Y) {
int opt = 0;
for(; X != Y; opt ++) {
if(Y > X && (Y & 1) == 0) Y >>= 1; // 如果是偶数先除以2为快
else if(Y > X) Y ++; // 如果奇数且 > X,加一
else return opt + X - Y; // 如果已经小于 X ,剩下也只有加一操作
}
return opt;
}
};