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
- 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.
- 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.
- 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.
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";
}
}