Medium

CodeMaster has just returned from shopping. He scanned the check of the items he bought and gave the resulting string to Ratiorg to figure out the total number of purchased items. Since Ratiorg is a bot he is definitely going to automate it, so he needs a program that sums up all the numbers which appear in the given input.

Help Ratiorg by writing a function that returns the sum of numbers that appear in the given inputString.

Example

For inputString = "2 apples, 12 oranges", the output should be
sumUpNumbers(inputString) = 14.

Input/Output

  • [execution time limit] 0.5 seconds (c)

  • [input] string inputString

    Guaranteed constraints:
    0 ≤ inputString.length ≤ 10^5.

  • [output] integer

[C] Syntax Tips

// Prints help message to the console
// Returns a string
char * helloWorld(char * name) {
    char * answer = malloc(strlen(name) + 8);
    printf("This prints to the console when you Run Tests");
    strcpy(answer, "Hello, ");
    strcat(answer, name);
    return answer;
}

더보기

Solution

int sumUpNumbers(char *inputString)
{
	int sum=0;

	for(int i=0;i<strlen(inputString);i++)
	{
		int number=0;

		while(isdigit(inputString[i]) && i<strlen(inputString))
		{
			number*=10;
			number+=inputString[i]-'0';
			i++;
		}

		sum+=number;
	}

	return sum;
}
728x90

'Codesignal' 카테고리의 다른 글

<Codesignal> digitsProduct  (0) 2020.04.06
<Codesignal> Different Squares  (0) 2020.04.06
<Codesignal> Valid Time  (0) 2020.04.06
<Codesignal> longestWord  (0) 2020.04.06
<Codesignal> deleteDigit  (0) 2020.04.06

+ Recent posts