在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 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 }
|
请发表评论