Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements