Minimum moves to reach target on a infinite line | Set 2 | Java code to find minimum moves to reach target ; Function to find minimum steps to reach target ; Handling negatives by symmetry ; Keep moving while sum is smaller i . e calculating n ; case 1 : d is even ; d is odd ; Driver code ; Function call
import java . lang . * ; class GFG { static int StepstoReachTarget ( int target ) { target = Math . abs ( target ) ; int n = ( int ) Math . ceil ( ( - 1.0 + ( int ) Math . sqrt ( 1 + 8.0 * target ) ) / 2 ) ; int sum = n * ( n + 1 ) / 2 ; if ( sum == target ) return n ; int d = sum - target ; if ( ( d & 1 ) == 0 ) return n ; else return n + ( ( n & 1 ) != 0 ? 2 : 1 ) ; } public static void main ( String [ ] arg ) { int target = 5 ; System . out . println ( StepstoReachTarget ( target ) ) ; } }