File tree 2 files changed +32
-0
lines changed
2 files changed +32
-0
lines changed Original file line number Diff line number Diff line change 572
572
749|[ Contain Virus] ( ./0749-contain-virus.js ) |Hard|
573
573
752|[ Open the Lock] ( ./0752-open-the-lock.js ) |Medium|
574
574
753|[ Cracking the Safe] ( ./0753-cracking-the-safe.js ) |Hard|
575
+ 754|[ Reach a Number] ( ./0754-reach-a-number.js ) |Medium|
575
576
762|[ Prime Number of Set Bits in Binary Representation] ( ./0762-prime-number-of-set-bits-in-binary-representation.js ) |Easy|
576
577
763|[ Partition Labels] ( ./0763-partition-labels.js ) |Medium|
577
578
783|[ Minimum Distance Between BST Nodes] ( ./0783-minimum-distance-between-bst-nodes.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 754. Reach a Number
3
+ * https://leetcode.com/problems/reach-a-number/
4
+ * Difficulty: Medium
5
+ *
6
+ * You are standing at position 0 on an infinite number line. There is a destination at
7
+ * position target.
8
+ *
9
+ * You can make some number of moves numMoves so that:
10
+ * - On each move, you can either go left or right.
11
+ * - During the ith move (starting from i == 1 to i == numMoves), you take i steps in the
12
+ * chosen direction.
13
+ *
14
+ * Given the integer target, return the minimum number of moves required (i.e., the minimum
15
+ * numMoves) to reach the destination.
16
+ */
17
+
18
+ /**
19
+ * @param {number } target
20
+ * @return {number }
21
+ */
22
+ var reachNumber = function ( target ) {
23
+ const absTarget = Math . abs ( target ) ;
24
+ let moves = Math . floor ( Math . sqrt ( 2 * absTarget ) ) ;
25
+
26
+ while ( true ) {
27
+ const sum = moves * ( moves + 1 ) / 2 ;
28
+ if ( sum >= absTarget && ( sum - absTarget ) % 2 === 0 ) return moves ;
29
+ moves ++ ;
30
+ }
31
+ } ;
You can’t perform that action at this time.
0 commit comments