I'm working on a programming challenge and the question is as follows:
Once Max found an electronic calculator from his grandfather Dovlet's chest. He noticed that the numbers were written with seven-segment indicators (https://en.wikipedia.org/wiki/Seven-segment_display).
Max starts to type all the values from a to b. After typing each number Max resets the calculator. Find the total number of segments printed on the calculator.
For example if a = 1 and b = 3 then at first the calculator will print 2 segments, then — 5 segments and at last it will print 5 segments. So the total number of printed segments is 12.
Input
The only line contains two integers a, b (1 ≤ a ≤ b ≤ 106) — the first and the last number typed by Max.
Output
Print the only integer a — the total number of printed segments.
Examples
input
1 3
output
12
input
10 15
output
39
Here's my attempt:
#include <iostream>
#include <unordered_map>
static std::unordered_map<char, int>
segment_count = {
{'1', 2},
{'2', 5},
{'3', 5},
{'4', 4},
{'5', 5},
{'6', 6},
{'7', 3},
{'8', 7},
{'9', 6},
{'0', 6}
};
int get_number_of_segments(char num) {
return segment_count[num];
}
int main() {
int start, end, sum = 0;
std::cin >> start >> end;
for(int i = start; i <= end; ++i) {
std::string current_num = std::to_string(i);
for(auto c: current_num) {
sum += get_number_of_segments(c);
}
}
std::cout << sum << '\n';
}
When I submit the code, it fails on a timeout for a test case (unknown test case). How can I make it more efficient? All tests should run in under 1 second.
One idea I've had is to store the numbers not in the "one's place" - these won't change.
For instance: in the sequence 10, 11, 12, 13, 14, ..., I don't need to lookup 1
each time. I only need to look at the last digit until I see a 9.
Perhaps there are better ways to do this, though.
Any help would be appreciated!