LeetCode Solutions
829. Consecutive Numbers Sum
Time: $O(n)$ Space: $O(1)$
class Solution {
public:
int consecutiveNumbersSum(int N) {
int ans = 0;
for (int i = 1, triangleNum = i; triangleNum <= N; ++i, triangleNum += i)
if ((N - triangleNum) % i == 0)
++ans;
return ans;
}
};
class Solution {
public int consecutiveNumbersSum(int N) {
int ans = 0;
for (int i = 1, triangleNum = i; triangleNum <= N; ++i, triangleNum += i)
if ((N - triangleNum) % i == 0)
++ans;
return ans;
}
}
class Solution:
def consecutiveNumbersSum(self, N: int) -> int:
ans = 0
i = 1
triangleNum = 1
while triangleNum <= N:
if (N - triangleNum) % i == 0:
ans += 1
i += 1
triangleNum += i
return ans