Leetcode 1317. Convert Integer to the Sum of Two No
LeetCode Problem 1317: Convert Integer to the Sum of Two No-Zero Integers
Given an integer n. You need to find two integers a and b such that:
a + b == na * b > 0 (both a and b must be positive)a nor b contains any zero digits.Return the two integers in the form of an array [a, b]. There may be multiple valid solutions. You can return any of them.
n be negative?
n is a positive integer.n?
The algorithm will primarily involve iterating through the numbers up to n, making the time complexity approximately O(n), but since we find a solution quickly, it is often much faster.
#include <vector>
#include <string>
// Function to check if a number contains any zero digits
bool hasZero(int num) {
while (num > 0) {
if (num % 10 == 0) {
return true;
}
num /= 10;
}
return false;
}
std::vector<int> getNoZeroIntegers(int n) {
for (int a = 1; a < n; ++a) {
int b = n - a;
if (!hasZero(a) && !hasZero(b)) {
return {a, b};
}
}
return {}; // Should never reach here for valid positive n.
}
hasZero, to check if a given integer contains the digit ‘0’.a starting from 1 to n-1.a, compute b as n - a.a and b do not contain the digit ‘0’ using the hasZero function.This approach ensures that we find a valid pair {a, b} that meet the criteria, with reasonable efficiency given the constraints of the problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?