首页 > 试题广场 >

设计一个函数1

[编程题]设计一个函数1
  • 热度指数:3084 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
设计一个函数,两个参数,第一个参数为整数的数组,第二个参数为标杆值,取数组中任意符合两个数相加为标杆值的下标相加到一起的值
传入一串字符串(如下例子所示),转义为数组,除去数组中最后一位数字作为标杆值,取数组中任意符合两个数相加为标杆值的下标,输出所有符合要求的下标的和。
如下解释:
value:0,1,5,11,17,16,2,5,10,30,12
index:1 3  6  8
输出结果为18

输入描述:
一串数字,逗号分割,最后一个值为标杆值
数组长度不超过1000,所有数均为不超过1e9的正整数。


输出描述:
结果值
示例1

输入

0,1,5,11,17,16,2,5,10,30,12

输出

18
示例2

输入

1,1,1,2

输出

6

说明

(0+1)+(0+2)+(1+2)=6
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char* const DELIM = ",";

// function prototype
int foo_bar(int* nums, const int numsSize, const int k);

int main(const int argc, const char* argv[]) {
  
  char input[10240] = "";
  fgets(input, 10240, stdin);
  
  int nums[1024], numsSize = 0, k;
  char* tok = strtok(input, DELIM);
  while (tok) {
    *(nums + numsSize++) = atoi(tok);
    tok = strtok(NULL, DELIM);
  }
  
  k = *(nums + --numsSize); // k == goal == target(阈值)
  return fprintf(stdout, "%d", foo_bar(nums, numsSize, k)), 0;
}

int foo_bar(int* nums, const int numsSize, const int k) {
  int i, j, s = 0;
  for (i = 0; i < numsSize; ++i)
    for (j = i + 1; j < numsSize; ++j)
      if (*(nums + i) + *(nums + j) == k)
        s += i + j;
  
  return s;
}

发表于 2021-07-16 12:42:53 回复(0)