100 Days of Code #Day3

Lakshmanan Subbiah
1 min readFeb 21, 2021

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

  1. 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
  2. Another edge case is that if x and y are equal we should return 0.
  3. And if X<Y continue dividing the Y by 2 and increment the number of steps
  4. But we might reach a situation where X*2 > Y since we are consciously decreasing Y by division.
  5. Here we have two options, One is to multiply x and 2 and find the difference of Y and X
  6. Or Decrement X until we reach the value which multiplied by 2 gives Y
  7. Return the minimal of 2 .
  8. Return the steps

Live Execution:

#100DaysofCode #Day3 #Challenge

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Responses (2)

Write a response

I have a little bit of confusion. If we are gonna give 0 for step argument in all places, why do we need to have it as an argument for calculateStep method?

--

Bro.. We can do it from Y to X. It would be done easily.
Int X=2
Int Y=3
Int min=0
While(Y>=X) {
If(Y%2==0){...

--