本文主要是介绍829. Consecutive Numbers Sum,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
The description of the problem
Given an integer n, return the number of ways you can write n as the sum of consecutive positive integers.来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/consecutive-numbers-sum
an example
Example 1:Input: n = 5
Output: 2
Explanation: 5 = 2 + 3
The intuition for this problem
The codes for above problem
#include <iostream>
using namespace std;
class Solution {
public:int consecutiveNumbersSum(int n) {int res = 0;int bound = 2*n;for (int k = 1; k * (k + 1) <= bound; ++k) {if (isKConservative(k, n)) ++res;}return res;}bool isKConservative(int k, int n) {if (k % 2 ==1 ){return n % k == 0;} else {return n % k != 0 && 2*n % k == 0;}}
};
int main()
{Solution s;cout << "res: " << s.consecutiveNumbersSum(5) << endl;return 0;
}
The second format:
#include <iostream>
using namespace std;
class Solution {
public:int consecutiveNumbersSum(int n) {int res = 0;int k = 1;while (k*(k+1) <= 2*n) {bool flag = false;if (k %2 ){if (n % k == 0) flag = true;} else {if ((n % k != 0) && ((2*n) % k == 0)) flag = true;}if (flag) res++;++k;}return res;}
};
int main()
{Solution s;cout << "res: " << s.consecutiveNumbersSum(5) << endl;return 0;
}
The results
$ ./test
res: 2
这篇关于829. Consecutive Numbers Sum的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!