First, I defined a function that checked whether an integer contains any 0 in its decimal representation:
bool checkZeroIntegers(int n) {
for (; n > 0; n /= 10) {
if (n % 10 == 0) {
return false;
}
}
return true;
}
Then, I simply iterated through all pairs of integers that sum to n,
running checkZeroIntegers on both integers present in the pair.
If both integers do not contain any zero integers,
then we can simply return the pair.
for (int i = 1; i < n; ++i) {
if (checkZeroIntegers(i) && checkZeroIntegers(n-i)) {
return {i, n-i};
}
}
code
class Solution {
public:
vector<int> getNoZeroIntegers(int n) {
for (int i = 1; i < n; ++i) {
if (checkZeroIntegers(i) && checkZeroIntegers(n-i)) {
return {i, n-i};
}
}
return {};
}
private:
bool checkZeroIntegers(int n) {
for (; n > 0; n /= 10) {
if (n % 10 == 0) {
return false;
}
}
return true;
}
};
complexity
- Time:
O(n log(n))- Space:
O(1)
learnings
- for memory sparse situation, can be better to forgo the
to_stringapproach and to just usedivisionandmoduloto accomplish the same thing
- e.g. instead of converting an integer to a
stringand iterating through itsnumbers, we can accomplish the same thing withdivisionandmodulooperation
time taken
- 4 minutes and 53 seconds
- i was carsick on the bus.... believe me guys...