- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- Count number of ways to reach destination in a Maze in C++
- Count number of ways to reach a given score in a Matrix in C++
- Count number of ways to jump to reach end in C++
- Find the number of jumps to reach X in the number line from zero in C++
- C Program for Minimum number of jumps to reach the end
- Count number of ways to reach a given score in a game
- Find the minimum number of steps to reach M from N in C++
- C++ Program to find out the number of jumps needed for a robot to reach a particular cell in a grid
- C++ program to count number of operations needed to reach n by paying coins
- C++ Program to find out the maximum number of moves to reach a unblocked cell to another unblocked cell in a grid
- Creating permutations to reach a target number, but reuse the provided numbers JavaScript
- C++ program to find minimum number of punches are needed to make way to reach target
- Find minimum steps required to reach the end of a matrix in C++
- Word Ladder (Length of shortest chain to reach a target word) in C++
- Find time taken for signal to reach all positions in a string - C++

Advertisements