Reach a Number in C++


Suppose you are standing at position 0 on an infinite number line. Now there is a goal at position target. Here in each move, you can either go to the left side or the right side. During the n-th move (starting from 1), you take n steps. We have to find the minimum number of steps required to reach the destination. So if the input is like target = 3, then we need 2 steps. From 0 to 1, from 1 to 3.

To solve this, we will follow these steps −

  • target := |target|, cnt := 0
  • while target > 0,
    • decrease cnt by 1
    • target := target –cnt
  • if target is even, then return cnt, otherwise cnt + 1 + cnt mod 2

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int reachNumber(int target) {
      target = abs(target);
      int cnt = 0;
      while(target > 0){
         target -= ++cnt;
      }
      return target % 2 == 0? cnt : cnt + 1 + cnt % 2;
   }
};
main(){
   Solution ob;
   cout << (ob.reachNumber(3));
}

Input

3

Output

2

Updated on: 04-May-2020

135 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements