1 changed files with 78 additions and 0 deletions
@ -0,0 +1,78 @@ |
|||||||
|
#include <stdio.h> |
||||||
|
#include <math.h> |
||||||
|
#include <string.h> |
||||||
|
|
||||||
|
#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;
|
||||||
|
// }
|
||||||
|
|
||||||
Loading…
Reference in new issue