easy
0 views

Space Separated Integers Sum In Python

Calculate the sum of all integers provided in a single space-separated line of input.

Understand the Problem

Problem Statement

Given a single line containing space-separated integers, your task is to compute and print the sum of all the integer values present in the input.

Constraints

  • The length of the input string is between 3 to 10,000 characters.
  • Each integer value ranges from -99,999 to 99,999.
  • The input consists of at least one integer.

Examples

Example 1
Input
100 -99 98 5
Output
104
Explanation

The integers are 100, -99, 98, and 5. Their sum is 100 + (-99) + 98 + 5 = 104.

Example 2
Input
100 200 -300 500 -450 -50
Output
0
Explanation

The integers are 100, 200, -300, 500, -450, and -50. Their sum is 100 + 200 + (-300) + 500 + (-450) + (-50) = 0.

Solution

#include <stdio.h>
#include <string.h>

int main() {
    char line[10001];
    fgets(line, sizeof(line), stdin);
    
    int sum = 0;
    char *token = strtok(line, " ");
    
    while (token != NULL) {
        int num = atoi(token);
        sum += num;
        token = strtok(NULL, " ");
    }
    
    printf("%d\n", sum);
    return 0;
}
Time:O(n), where n is the length of the input string
Space:O(1), not counting the input buffer
Approach:

This C solution reads the entire input line using fgets. It then uses strtok to split the string by spaces, extracting each token. Each token is converted to an integer using atoi, and the value is added to the running sum. Finally, the total sum is printed.

Visual Explanation

Loading diagram...