829. Consecutive Numbers Sum
829. Consecutive Numbers Sum
題目大意:
給定一個正整數N,問有多少種連續整數的組合相加為N。
for example:N = 5, 5 = 5 = 2 + 3, so answer is 2
解題思路:
首先,最小的兩個連續正整數相加1+2=3,
大點的就是2+3=5=1+2+2,再大點3+4=7=2+3+2=1+2+(2+2),
從中可以看出如果存在兩個連續正整數之和等於N,
那麼必然N=1+2+2k(k為正整數),N-(1+2)可以整除2,即(N-(1+2))%2 == 0.
往下推,n個連續正整數就是,(N-(1+2+...+n))%n == 0
注意:
None
複雜度:
Time Complexity:
Space Complexity:
Code示例:
class Solution {
public int consecutiveNumbersSum(int N) {
int ans = 1, sum = 1;
//一個連續正整數即N本身,我們從2開始逐一判斷,true則加1
for (int i = 2; (sum+=i)<=N; i++) {
if ((N-sum) % i == 0) ans++;
}
return ans;
}
}
相關文章
- Sum of Consecutive Prime Numbers POJ - 2739(線性尤拉篩+尺取法)
- Leetcode 967 Numbers With Same Consecutive DifferencesLeetCode
- Sum of Square Numbers 平方數之和
- 129-Sum Root to Leaf Numbers
- LeetCode 129. Sum Root to Leaf NumbersLeetCode
- LeetCode之Sum of Even Numbers After Queries(Kotlin)LeetCodeKotlin
- 演算法練習--LeetCode--129. Sum Root to Leaf Numbers; Runtime: 8 ms100%演算法LeetCode
- Leetcode 298 Binary Tree Longest Consecutive SequenceLeetCode
- Reversed Numbers
- 400多種Numbers模板 DesiGN for Numbers Templates for macMac
- Collecting Numbers II
- Codeforces - Jzzhu and Numbers
- different random numbers generatorrandom
- 【Lintcode】1267. Lexicographical Numbers
- 165. Compare Version Numbers
- Leetcode 165 Compare Version NumbersLeetCode
- Find All Numbers Disappeared in an ArrayAPP
- LeetCode 2 Add Two NumbersLeetCode
- 201-Bitwise AND of Numbers Range
- 秒殺 2Sum 3Sum 4Sum 演算法題演算法
- GCD SUMGC
- Sum Problem
- 集合sum
- 15+18、3Sum 4Sum
- CF1406E Deleting Numbers
- B. Numbers Box(思維)
- C. k-Amazing Numbers
- LeetCode-2 Add Two NumbersLeetCode
- Self Dividing Numbers 自除數
- Note 886532 - Pricing: Displaying and rounding numbers
- LeetCode 2. Add Two NumbersLeetCode
- Add_Two_Numbers python 求解Python
- Range Minimum Sum
- B - Minimum Sum
- Missing Subsequence Sum
- Path Sum III
- Leetcode Path SumLeetCode
- leetcode Sum系列LeetCode