[Swift]LeetCode829. 連續整數求和 | Consecutive Numbers Sum

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-xuuojjzp-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

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

Example 1:github

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:spa

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

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


給定一個正整數 N,試求有多少組連續正整數知足全部數字之和爲 N?htm

示例 1:blog

輸入: 5
輸出: 2
解釋: 5 = 5 = 2 + 3,共有兩組連續整數([5],[2,3])求和後爲 5。

示例 2:get

輸入: 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 }
相關文章
相關標籤/搜索