Skip to content

Commit 49deb06

Browse files
committedMar 13, 2025
Add solution #754
1 parent b62f1c7 commit 49deb06

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -572,6 +572,7 @@
572572
749|[Contain Virus](./0749-contain-virus.js)|Hard|
573573
752|[Open the Lock](./0752-open-the-lock.js)|Medium|
574574
753|[Cracking the Safe](./0753-cracking-the-safe.js)|Hard|
575+
754|[Reach a Number](./0754-reach-a-number.js)|Medium|
575576
762|[Prime Number of Set Bits in Binary Representation](./0762-prime-number-of-set-bits-in-binary-representation.js)|Easy|
576577
763|[Partition Labels](./0763-partition-labels.js)|Medium|
577578
783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy|

‎solutions/0754-reach-a-number.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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+
};

0 commit comments

Comments
 (0)
Please sign in to comment.