Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 7506e4d

Browse files
committed
Solve #264
1 parent 6a8088b commit 7506e4d

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,3 +209,4 @@ mod n0257_binary_tree_paths;
209209
mod n0258_add_digits;
210210
mod n0260_single_number_iii;
211211
mod n0263_ugly_number;
212+
mod n0264_ugly_number_ii;

src/n0264_ugly_number_ii.rs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/**
2+
* [264] Ugly Number II
3+
*
4+
* Write a program to find the n-th ugly number.
5+
*
6+
* Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
7+
*
8+
* Example:
9+
*
10+
*
11+
* Input: n = 10
12+
* Output: 12
13+
* Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
14+
*
15+
* Note:
16+
*
17+
* <ol>
18+
* 1 is typically treated as an ugly number.
19+
* n does not exceed 1690.
20+
* </ol>
21+
*/
22+
pub struct Solution {}
23+
24+
// submission codes start here
25+
26+
impl Solution {
27+
pub fn nth_ugly_number(n: i32) -> i32 {
28+
let mut base2 = 0;
29+
let mut base3 = 0;
30+
let mut base5 = 0;
31+
let mut ugly = vec![1;1];
32+
for _ in 1..n {
33+
let next2 = ugly[base2] * 2;
34+
let next3 = ugly[base3] * 3;
35+
let next5 = ugly[base5] * 5;
36+
let next = i32::min(next2, i32::min(next3, next5));
37+
if next2 == next { base2 += 1 }
38+
if next3 == next { base3 += 1 }
39+
if next5 == next { base5 += 1 }
40+
ugly.push(next)
41+
}
42+
*ugly.last().unwrap()
43+
}
44+
}
45+
46+
// submission codes end
47+
48+
#[cfg(test)]
49+
mod tests {
50+
use super::*;
51+
52+
#[test]
53+
fn test_264() {
54+
assert_eq!(Solution::nth_ugly_number(1), 1);
55+
assert_eq!(Solution::nth_ugly_number(10), 12);
56+
}
57+
}

0 commit comments

Comments
 (0)