今天的打卡章节为《C语言入门100例》(第2例) 求和;
附上链接:【第02题】给定 n,求 1 + 2 + 3 + ... + n 的和 | 四种解法
全文目录
主要内容
? ? ?求和方法:
力扣习题:
????????剑指 Offer 64. 求1+2+…+n
????????剑指 Offer 57 - II. 和为s的连续正数序列
主要内容? ? ?
????????求和方法:
? ? ? ? 解法一:循环枚举
#include <stdio.h>
int main() {
int n, ans;
while (scanf("%d", &n) != EOF) {
ans = 0;
while(n) {
ans += n;
--n;
}
printf("%d\n\n", ans);
}
return 0;
}
? ? ? ? 解法二:奇偶性判断
#include <stdio.h>
int main() {
int n, ans;
while (scanf("%d", &n) != EOF) {
if(n % 2 == 0) {
ans = n / 2 * (n+1);
} else {
ans = (n+1) / 2 * n;
}
printf("%d\n\n", ans);
}
return 0;
}
? ? ? ? 解法三:无符号整型
#include <stdio.h>
int main() {
unsigned int n;
while (scanf("%u", &n) != EOF) {
unsigned int ans = n * (n + 1) / 2;
printf("%u\n\n", ans);
}
return 0;
}
? ? ? ? 解法四:64位整型
#include <stdio.h>
int main() {
long long n;
while (scanf("%lld", &n) != EOF) {
long long ans = n * (n + 1) / 2;
printf("%lld\n\n", ans);
}
return 0;
}
力扣习题:
直接递归相加
int sumNums(int n){
if(n==0)
{
return 0;
}
return n+sumNums(n-1);
}
n的和只能在n/2 + 1之前产生,利用双指针遍历1到n/2查找符合的条件,具体看代码。
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int** findContinuousSequence(int target, int* returnSize, int** returnColumnSizes) {
if (target < 1) {
return NULL;
}
int** ans = (int**)malloc(sizeof(int*) * target);
*returnColumnSizes = (int*)malloc(sizeof(int) * target);
int left = 1, right = 1, sum = 0, len = target / 2;
*returnSize = 0;
while (left <= len) {
if (sum == target) {
(*returnColumnSizes)[*returnSize] = right - left;
ans[*returnSize] = (int*)malloc(sizeof(int) * (right - left));
for (int i = left; i < right; i++) {
ans[*returnSize][i - left] = i;
}
(*returnSize)++;
sum -= left++;
}
if (sum < target) {
sum += right++;
}
if (sum > target){
sum -= left++;
}
}
return ans;
}
|