cppAcademy
FROM LEARNING TO COMPETING

Beginner.
Your first challenges.

Bulgarian Informatics Group E · 2007–2026

270 independently explained problems: 54 Municipal, 54 Regional, 105 National Olympiad tasks and 57 Autumn Tournament tasks. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group E also includes challenging national-level problems. Years follow Arena’s competition-season labels. Source clarifications are noted on affected tasks.
GROUP E2019 · EasyString parsing

Numbers Between Letters

Autumn Tournament (2019)

Submission name: nums_between_chars.cpp

Problem summary

Find every number in a four-character string of Latin letters and digits. Each maximal consecutive run of digits is one number. In left-to-right order, print each number multiplied by N. If no number occurs, print N/A.

Input

Line 1: integer N. Line 2: exactly four letters and/or digits, without spaces.

Output

One product per line, or N/A if the string contains only letters.

Constraints

0 ≤ N < 100; the string contains exactly four characters.

Worked example

First official statement sample.

Input

3
j15Q

Output

45

Solution analysis

  1. Scan from left to right. Skip letters. When a digit is found, start a number at zero and repeatedly update value = 10 × value + digit while digits continue.
  2. Print N × value after consuming the whole run. Track whether any run has been found; this is separate from whether its value or product is zero.
  3. For j15Q, the run 15 gives 3 × 15 = 45. For S2t3 and N = 12, the two runs produce 24 and 36. For an all-letter string, print N/A.

Why it works

At the start of each scan step all earlier characters are fully processed. A letter belongs to no number; a digit starts the next maximal run, which the inner loop consumes completely and evaluates by decimal place value. Thus every number is printed exactly once and in order. The found flag is false exactly when there are no runs.

Complexity: O(s) time and O(1) extra space, where s = 4.

Watch out. Print zero products normally, including when N = 0. Consecutive digits form one number, and leading zeros do not split a run.

Commented C++17 solution

An independently written complete program with standard headers.

#include<iostream>
#include<string>
using namespace std;
bool isDigit(char c){
    return c>='0'&&c<='9';
}
int main(){
    int n;
    string text;
    cin>>n>>text;
    bool found=false;
    size_t i=0;
    while(i<text.size()){
        if(!isDigit(text[i])){
            ++i;
            continue;
        }
        int value=0;
        // Consume one complete consecutive run of digits.
        while(i<text.size()&&isDigit(text[i])){
            value=value*10+(text[i]-'0');
            ++i;
        }
        cout<<n*value<<'\n';
        found=true;
    }
    if(!found){
        cout<<"N/A\n";
    }
}

Source: Arena Olimpiici ↗