3546. Equal Sum Grid Partition I - Solver explained with examples and C++ solution.

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

No-Zero integer is a positive integer that does not contain any 0 in its decimal representation.

Given an integer n, return a list of two integers [a, b] where:

  • a and b are No-Zero integers.
  • a + b = n

The test cases are generated so that there is at least one valid solution. If there are many valid solutions, you can return any of them.

Example 1:

Input: n = 2
Output: [1,1]
Explanation: Let a = 1 and b = 1.
Both a and b are no-zero integers, and a + b = 2 = n.

Example 2:

Input: n = 11
Output: [2,9]
Explanation: Let a = 2 and b = 9.
Both a and b are no-zero integers, and a + b = 11 = n.
Note that there are other valid answers as [8, 3] that can be accepted.

Constraints:

  • 2 <= n <= 104
class Solution {
public:
    bool hasZero(int n){
        while(n>0){
            if(n%10==0)
                return true;
            n /= 10;
        }
        return false;
    }
    vector<int> getNoZeroIntegers(int n) {
        vector<int> result;
        result.reserve(n);
        for (int idx = 1; idx <= n; idx++) {
            int x = idx;
            int y = n - idx;
            if (!hasZero(x) and !hasZero(y)) {
                result.push_back(x);
                result.push_back(y);
                return result;
            }
        }
        return result;
    }
};

Complexity:

Space → O(n * log n)

Time → O(1)

Leave a Reply

Your email address will not be published. Required fields are marked *