[Swift]LeetCode829. 连续整数求和 | Consecutive Numbers Sum
发布时间:2020-12-14 04:59:21 所属栏目:百科 来源:网络整理
导读:Given a positive integer? N ,how many ways can we write it as a sum of?consecutive positive integers? Example 1: Input: 5Output: 2Explanation: 5 = 5 = 2 + 3 Example 2: Input: 9Output: 3Explanation: 9 = 9 = 4 + 5 = 2 + 3 + 4 Example 3: Inpu
Given a positive integer? 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: 输入: 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 说明:? 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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容