Quantcast
Channel: 书影 - Entries for the tag leetcode
Viewing all articles
Browse latest Browse all 559

[LeetCode]Consecutive Numbers Sum

$
0
0

题目描述:

LeetCode 829. Consecutive Numbers Sum

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:

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

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

题目大意:

给定正整数N,将其表示为若干连续整数之和。求可以找到多少种这样的组合。

解题思路:

枚举连续整数的个数c

当c为奇数时, floor(N / c) 为第(c + 1) / 2个数

当c为偶数时,floor(N / c)为第c / 2个数

综上,floor(N / c)为第c / 2 + c % 2个数,并且floor(N / c) ≥ c / 2 + c % 2

c符合下列两种情况时,存在一组长度为c的连续整数和为N

c为奇数,并且N可以整除c

c为偶数,并且floor(N / c) * c + c / 2 == N

Python代码:

class Solution(object):
    def consecutiveNumbersSum(self, N):
        """
        :type N: int
        :rtype: int
        """
        ans = c = 0
        while True:
            c += 1
            if N / c < c / 2 + c % 2:
                break
            if c % 2 and N % c == 0:
                ans += 1
            elif c % 2 == 0 and (N / c) * c + c / 2 == N:
                ans += 1
        return ans

 


Viewing all articles
Browse latest Browse all 559

Trending Articles