From 4b179b96e5624f3d31e4440e2b8bedf35b11a808 Mon Sep 17 00:00:00 2001 From: chodak166 Date: Sat, 29 Jul 2023 09:12:06 +0200 Subject: [PATCH] Added samsung t1 task solution --- samsung/t1/main.c | 78 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 samsung/t1/main.c diff --git a/samsung/t1/main.c b/samsung/t1/main.c new file mode 100644 index 0000000..d912479 --- /dev/null +++ b/samsung/t1/main.c @@ -0,0 +1,78 @@ +#include +#include +#include + +#define BIG_SIZE (400000) +void test(int actual, int expected); + +// NOTE: since N is not given, we assume standard string termination (\0) + +int solution(char* str) +{ + int sum = 0; + while (str[0] == '0' // skip leading zeros + && str[0] != '\n') { // handle zero-only strings + ++str; + } + while (str[0] != '\0') { + if (str[0] == '0') { + sum += 1; + } + else { + sum += 2; + } + ++str; + } + return sum ? sum -1 : 0; +} + +int main() +{ + test(solution("0"), 0); + test(solution("00000"), 0); + test(solution("1"), 1); + test(solution("011100"), 7); + test(solution("111"), 5); + test(solution("1111010101111"), 22); + + char str[BIG_SIZE+1]; + memset(str, '1', BIG_SIZE+1); + str[BIG_SIZE] = '\0'; + test(solution(str), 799999); + + printf("Done\n"); +} + +// ----- + +void test(int actual, int expected) +{ + if (actual != expected) { + printf("Test failed, expected %i, got %i\n", expected, actual); + } + else { + printf("Test passed (expected %i, got %i)\n", expected, actual); + } +} + +// alternative solution: +// int solution(char* str) +// { +// int sum = 0; +// int i = 0; +// while (str[i] == '0' && str[i] != '\n') { +// ++i; +// } + +// while (str[i] != '\0') { +// if (str[i] == '0') { +// sum += 1; +// } +// else { +// sum += 2; +// } +// ++i; +// } +// return sum ? sum -1 : 0; +// } +