100 Days of Code #Day3
As I am running a bit late today, I planned to solve the today’s leet code challenge itself.
On a broken calculator that has a number showing on its display, we can perform two operations:
- Double: Multiply the number on the display by 2, or;
- Decrement: Subtract 1 from the number on the display.
Initially, the calculator is displaying the number X
.
Return the minimum number of operations needed to display the number Y
.
Example 1:
Input: X = 2, Y = 3
Output: 2
Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.
Ref: https://leetcode.com/problems/broken-calculator/
At the base level this problem looks complex but we can understand it by breaking down the cases
- X can perform only two operations multiply by 2 or decrement by 1. So if Y is less than X only Decrement operation can be performed
- Another edge case is that if x and y are equal we should return 0.
- And if X<Y continue dividing the Y by 2 and increment the number of steps
- But we might reach a situation where X*2 > Y since we are consciously decreasing Y by division.
- Here we have two options, One is to multiply x and 2 and find the difference of Y and X
- Or Decrement X until we reach the value which multiplied by 2 gives Y
- Return the minimal of 2 .
- Return the steps
Live Execution:
#100DaysofCode #Day3 #Challenge