-
Notifications
You must be signed in to change notification settings - Fork 0
/
prime-number-of-set-bits-in-binary-representation.rs
50 lines (45 loc) · 1.29 KB
/
prime-number-of-set-bits-in-binary-representation.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
struct Solution;
impl Solution {
fn impl1(left: i32, right: i32) -> i32 {
let mut count = 0;
for i in left..=right {
match format!("{:b}", i)
.chars()
.filter(|&x| x == '1')
.collect::<String>()
.len()
{
2 | 3 | 5 | 7 | 11 | 13 | 17 | 19 => count += 1,
_ => continue,
}
}
count
}
fn impl2(left: i32, right: i32) -> i32 {
(left..=right).fold(0, |count, x| match x.count_ones() {
2 | 3 | 5 | 7 | 11 | 13 | 17 | 19 => count + 1,
_ => count,
})
}
pub fn count_prime_set_bits(left: i32, right: i32) -> i32 {
Solution::impl1(left, right)
}
}
fn main() {
println!("{}", Solution::count_prime_set_bits(6, 10));
println!("{}", Solution::impl1(10, 15));
println!("{}", Solution::impl2(990, 1048));
}
#[cfg(test)]
mod tests {
use crate::Solution;
#[test]
fn test() {
assert_eq!(Solution::impl1(6, 10), 4);
assert_eq!(Solution::impl1(10, 15), 5);
assert_eq!(Solution::impl1(990, 1048), 28);
assert_eq!(Solution::impl2(6, 10), 4);
assert_eq!(Solution::impl2(10, 15), 5);
assert_eq!(Solution::impl2(990, 1048), 28);
}
}