[Swift]LeetCode829. 连续整数求和 | Consecutive Numbers Sum

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: https://www.cnblogs.com/strengthen/p/10570866.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

Given a positive integer N, how many ways can we write it as a sum of consecutive positive integers?

Example 1:

Input: 5
Output: 2
Explanation: 5 = 5 = 2 + 3

Example 2:

Input: 9
Output: 3
Explanation: 9 = 9 = 4 + 5 = 2 + 3 + 4

Example 3:

Input: 15
Output: 4
Explanation: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5

Note: 1 <= N <= 10 ^ 9.


给定一个正整数 N,试求有多少组连续正整数满足所有数字之和为 N?

示例 1:

输入: 5
输出: 2
解释: 5 = 5 = 2 + 3,共有两组连续整数([5],[2,3])求和后为 5。

示例 2:

输入: 9
输出: 3
解释: 9 = 9 = 4 + 5 = 2 + 3 + 4

示例 3:

输入: 15
输出: 4
解释: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5

说明: 1 <= N <= 10 ^ 9


24ms

 1 class Solution {
 2     func consecutiveNumbersSum(_ N: Int) -> Int {
 3         let num : CGFloat = CGFloat(N);
 4         var n : CGFloat  = 1;
 5         var a : CGFloat = 10;
 6         var m = 0;
 7         while (a>=1) {
 8             a = CGFloat(num/n - (n-1)/2);
 9             let b : Int = Int(a);
10             if (a == CGFloat(b) && a >= 1) {
11                 m += 1;
12             }
13             n += 1;
14         }
15         return m;
16     }
17 }

24ms

 1 class Solution {
 2     func consecutiveNumbersSum(_ N: Int) -> Int {
 3         var count = 0
 4         var length = 1
 5         while 2*N >= length*length + length {
 6             if (2*N+length-length*length) % (2*length) == 0 {
 7                 count += 1
 8             }
 9             length = length + 1
10         }
11         return count
12     }
13 }

Runtime: 32 ms
Memory Usage: 18.4 MB
 1 class Solution {
 2     func consecutiveNumbersSum(_ N: Int) -> Int {
 3         var ans:Int = 1
 4         var i:Int = 2
 5         while(i * (i + 1) / 2 <= N)
 6         {
 7             if (N - i * (i + 1) / 2) % i == 0
 8             {
 9                 ans += 1
10             }
11             i += 1
12         }
13         return ans
14     }
15 }
原文地址:https://www.cnblogs.com/strengthen/p/10570866.html