-
Notifications
You must be signed in to change notification settings - Fork 3
/
03-consecutive-numbers-sum.rs
40 lines (39 loc) · 1.11 KB
/
03-consecutive-numbers-sum.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
// https://leetcode.cn/problems/consecutive-numbers-sum/
impl Solution {
pub fn consecutive_numbers_sum(n: i32) -> i32 {
let mut ans = 0;
let mut i = 0;
let n_is_even = n & 1 == 0;
while i * (i + 1) / 2 <= n {
i += 1;
let i_is_even = i & 1 == 0;
let i_div_2_is_even = i >> 1 & 1 == 0;
if i_is_even && i_div_2_is_even && !n_is_even {
// only even
continue;
}
if i_is_even && !i_div_2_is_even && n_is_even {
// only odd
continue;
}
let mut cur = i;
if cur & 1 == 0 {
cur >>= 1;
}
if n % cur == 0 {
let mut div = n / cur;
let div_is_even = div & 1 == 0;
if div_is_even && i_is_even {
continue;
}
if !i_is_even {
div <<= 1;
}
if div >= (i + 1) {
ans += 1;
}
}
}
ans
}
}