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
, return an array ans
of length 2, where:
ans[0]
and ans[1]
are integers andn == ans[0] + ans[1]
ans[0]
nor ans[1]
contains any zero digits.n
be negative?
n
is a positive integer (1 <= n <= 10^4
).To solve this problem:
a
starting from 1 to n-1
.a
, calculate b
as n - a
.a
and b
do not contain the digit ‘0’.a
and b
both do not contain ‘0’, return the pair [a, b]
.We will need a helper function hasZero(int num)
that checks if a given integer contains the digit ‘0’.
The time complexity is O(n * k), where n
is the given integer, and k
is the maximum number of digits in n
(which is negligible compared to n
).
public class Solution {
public int[] getNoZeroIntegers(int n) {
for (int a = 1; a < n; a++) {
int b = n - a;
if (!hasZero(a) && !hasZero(b)) {
return new int[]{a, b};
}
}
// The problem guarantees a solution, so we should never reach here.
return new int[]{-1, -1};
}
private boolean hasZero(int num) {
while (num > 0) {
if (num % 10 == 0) {
return true;
}
num /= 10;
}
return false;
}
public static void main(String[] args) {
Solution sol = new Solution();
int n = 1010;
int[] result = sol.getNoZeroIntegers(n);
System.out.println("Result: [" + result[0] + ", " + result[1] + "]");
}
}
a
from 1 to n-1
.a
, we calculate b
as n - a
.hasZero
checks if any number contains the digit zero.a
and b
pass the check, we return the pair [a, b]
.This approach ensures that we find the required no-zero integers efficiently.
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?