Skip to content

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

Description

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

 

Solutions

Solution: Math

  • Time complexity: O(1)
  • Space complexity: O(1)

 

JavaScript

js
/**
 * @param {number} n
 * @return {number[]}
 */
const getNoZeroIntegers = function (n) {
  let a = 0;
  let b = 0;
  let carry = 0;
  let digit = 0;

  while (n) {
    let num = (n % 10) - carry;

    n = Math.floor(n / 10);

    if (num < 0) {
      num += 10;
      n -= 1;
    }

    if (n <= 0 && num <= 0) return [a, b];

    if (num === 1 && n) {
      a += 2 * 10 ** digit;
      b += 9 * 10 ** digit;
      carry = 1;
    } else if (num === 0) {
      a += 5 * 10 ** digit;
      b += 5 * 10 ** digit;
      carry = 1;
    } else {
      const half = Math.floor(num / 2);

      a += half * 10 ** digit;
      b += (num - half) * 10 ** digit;
      carry = 0;
    }

    digit += 1;
  }

  return [a, b];
};

Released under the MIT license