LeetCode 1317. Convert Integer to the Sum of Two No-Zero Integers.

🔹 Approach Discussion

1️⃣ Problem Restatement

We are given an integer n.
We need to find two integers [a, b] such that:

a + b = n

Neither a nor b contains the digit 0.

2️⃣ Intuition

The simplest way is to try all possible values of a.

For each a, compute b = n - a.

Check if both a and b contain no zero digit.

The first valid pair we find can be returned immediately (since the problem guarantees a solution exists).

3️⃣ Java Implementation
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};
            }
        }
        return new int[]{-1, -1}; // This line is never actually reached
    }

    // helper function: checks if a number contains zero
    private boolean hasZero(int x) {
        while (x > 0) {
            if (x % 10 == 0) return true;
            x /= 10;
        }
        return false;
    }
}

4️⃣ Example Walkthrough

Input: n = 11

Try a = 2, then b = 9.

Check hasZero(2)false, hasZero(9)false.

Both are valid → return [2, 9].

5️⃣ Complexity Analysis

Time Complexity: O(n * d)

n for the loop, and d = number of digits when checking for zeros.

Since n ≤ 10^4, this is efficient enough.

Space Complexity: O(1).

6️⃣ Optimizations

You can try greedy strategies (e.g., start with a = n - 1, b = 1) and adjust if any number contains zero.

But given the constraints, the brute force loop is simple, readable, and passes all test cases.

thank you

Comments (2)