Let's make this one less mysterious. For 1295. Find Numbers with Even Number of Digits, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: straightforward implementation.
Guide
When?
This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are findNumbers.
Guide
Why?
The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- Return the value that represents the fully processed input.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01/*
02Runtime: 4 ms, faster than 98.29% of C++ online submissions for Find Numbers with Even Number of Digits.
03Memory Usage: 8.9 MB, less than 100.00% of C++ online submissions for Find Numbers with Even Number of Digits.
04*/
05class Solution {
06public:
07 int findNumbers(vector<int>& nums) {
08 int digit = 0, ans = 0;
09
10 for(int num : nums){
11 digit = 0;
12
13 while(num){
14 num /= 10;
15 digit++;
16 }
17
18 if(digit % 2 == 0){
19 ans++;
20 }
21 }
22
23 return ans;
24 }
25};
Cost