728x90
www.hackerrank.com/challenges/divisible-sum-pairs/problem
int divisibleSumPairs(int n, int k, int ar_count, int* ar) {
int pair=0;
int sum=0;
for(int i=0;i<ar_count-1;i++){
for(int j=i+1;j<ar_count;j++){
sum = ar[i] + ar[j];
if(sum % k==0) pair+=1;
sum=0;
}
}
return pair;
}
△ 작성한 부분의 코드
같은 인덱스의 값을 두 번 더하거나 (n,m)과 (m,n)으로 합이 중복될 수 있기 때문에 이중 for문의 조건을 주의해서 작성해야 한다.
바깥 for문에서 ar_count -1 로 조건을 지정해 마지막 인덱스를 합에 포함시키는 경우에 대해 주의해야한다.
#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* readline();
char** split_string(char*);
// Complete the divisibleSumPairs function below.
int divisibleSumPairs(int n, int k, int ar_count, int* ar) {
int pair=0;
int sum=0;
for(int i=0;i<ar_count-1;i++){
for(int j=i+1;j<ar_count;j++){
sum = ar[i] + ar[j];
if(sum % k==0) pair+=1;
sum=0;
}
}
return pair;
}
int main()
{
FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");
char** nk = split_string(readline());
char* n_endptr;
char* n_str = nk[0];
int n = strtol(n_str, &n_endptr, 10);
if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); }
char* k_endptr;
char* k_str = nk[1];
int k = strtol(k_str, &k_endptr, 10);
if (k_endptr == k_str || *k_endptr != '\0') { exit(EXIT_FAILURE); }
char** ar_temp = split_string(readline());
int* ar = malloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
char* ar_item_endptr;
char* ar_item_str = *(ar_temp + i);
int ar_item = strtol(ar_item_str, &ar_item_endptr, 10);
if (ar_item_endptr == ar_item_str || *ar_item_endptr != '\0') { exit(EXIT_FAILURE); }
*(ar + i) = ar_item;
}
int ar_count = n;
int result = divisibleSumPairs(n, k, ar_count, ar);
fprintf(fptr, "%d\n", result);
fclose(fptr);
return 0;
}
char* readline() {
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);
while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);
if (!line) { break; }
data_length += strlen(cursor);
if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; }
size_t new_length = alloc_length << 1;
data = realloc(data, new_length);
if (!data) { break; }
alloc_length = new_length;
}
if (data[data_length - 1] == '\n') {
data[data_length - 1] = '\0';
}
data = realloc(data, data_length);
return data;
}
char** split_string(char* str) {
char** splits = NULL;
char* token = strtok(str, " ");
int spaces = 0;
while (token) {
splits = realloc(splits, sizeof(char*) * ++spaces);
if (!splits) {
return splits;
}
splits[spaces - 1] = token;
token = strtok(NULL, " ");
}
return splits;
}
SMALL
'Programming > C C++' 카테고리의 다른 글
Migratory Birds (0) | 2020.09.20 |
---|---|
[DS] Insert a node at a specific position in a linked list (0) | 2020.09.13 |
[DS] Insert a node at the head of a linked list (0) | 2020.08.30 |
Birthday Chocolate (0) | 2020.08.30 |
[DS] Insert a Node at the Tail of a Linked List (0) | 2020.08.23 |