Skip to content

Commit bba180a

Browse files
committedApr 6, 2025
Add solution #1201
1 parent cb7f392 commit bba180a

File tree

2 files changed

+52
-1
lines changed

2 files changed

+52
-1
lines changed
 

‎README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,176 LeetCode solutions in JavaScript
1+
# 1,177 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -926,6 +926,7 @@
926926
1191|[K-Concatenation Maximum Sum](./solutions/1191-k-concatenation-maximum-sum.js)|Medium|
927927
1192|[Critical Connections in a Network](./solutions/1192-critical-connections-in-a-network.js)|Hard|
928928
1200|[Minimum Absolute Difference](./solutions/1200-minimum-absolute-difference.js)|Easy|
929+
1201|[Ugly Number III](./solutions/1201-ugly-number-iii.js)|Medium|
929930
1206|[Design Skiplist](./solutions/1206-design-skiplist.js)|Hard|
930931
1207|[Unique Number of Occurrences](./solutions/1207-unique-number-of-occurrences.js)|Easy|
931932
1208|[Get Equal Substrings Within Budget](./solutions/1208-get-equal-substrings-within-budget.js)|Medium|

‎solutions/1201-ugly-number-iii.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* 1201. Ugly Number III
3+
* https://leetcode.com/problems/ugly-number-iii/
4+
* Difficulty: Medium
5+
*
6+
* An ugly number is a positive integer that is divisible by a, b, or c.
7+
*
8+
* Given four integers n, a, b, and c, return the nth ugly number.
9+
*/
10+
11+
/**
12+
* @param {number} n
13+
* @param {number} a
14+
* @param {number} b
15+
* @param {number} c
16+
* @return {number}
17+
*/
18+
var nthUglyNumber = function(n, a, b, c) {
19+
const ab = lcm(a, b);
20+
const bc = lcm(b, c);
21+
const ac = lcm(a, c);
22+
const abc = lcm(ab, c);
23+
let left = 1;
24+
let right = 2 * 10**9;
25+
26+
while (left < right) {
27+
const mid = left + Math.floor((right - left) / 2);
28+
if (countUgly(mid) < n) {
29+
left = mid + 1;
30+
} else {
31+
right = mid;
32+
}
33+
}
34+
35+
return left;
36+
37+
function lcm(x, y) {
38+
return (x * y) / gcd(x, y);
39+
}
40+
41+
function gcd(x, y) {
42+
return y === 0 ? x : gcd(y, x % y);
43+
}
44+
45+
function countUgly(num) {
46+
return Math.floor(num / a) + Math.floor(num / b) + Math.floor(num / c)
47+
- Math.floor(num / ab) - Math.floor(num / bc) - Math.floor(num / ac)
48+
+ Math.floor(num / abc);
49+
}
50+
};

0 commit comments

Comments
 (0)
Please sign in to comment.