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

题目如下:

Given an integer n. No-Zero integer is a positive integer which doesn't contain any 0 in its decimal representation.

Return a list of two integers [A, B] where:

  • A and B are No-Zero integers.
  • A + B = n

It's guarateed 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: A = 1, B = 1. A + B = n and both A and B don't contain any 0 in their decimal representation.

Example 2:

Input: n = 11
Output: [2,9]

Example 3:

Input: n = 10000
Output: [1,9999]

Example 4:

Input: n = 69
Output: [1,68]

Example 5:

Input: n = 1010
Output: [11,999]

Constraints:

  • 2 <= n <= 10^4

解题思路:从n的个位开始,依次对每一位进行拆分。拆分的原则也很简单,如果某一位的值是x,那就拆成1和x-1。特别要注意借位,如果某一位的值是0或1,都需要向后一位借位。

代码如下:

class Solution(object):
    def getNoZeroIntegers(self, n):
        """
        :type n: int
        :rtype: List[int]
        """
        num1 = ''
        num2 = ''
        nl = map(int, str(n))
        for i in range(len(nl)-1,-1,-1):
            if nl[i] > 1:
                num1 = '1' + num1
                num2 = str(nl[i] - 1) + num2
            elif nl[i] == 1 and i != 0:
                num1 = '2' + num1
                num2 = '9' + num2
                nl[i - 1] -= 1
            elif nl[i] == 1 and i == 0:
                num1 = '1' + num1
            elif nl[i] == 0 and i > 0:
                num1 = '1' + num1
                num2 = '9' + num2
                nl[i-1] -= 1
            elif nl[i] == -1:
                num1 = '1' + num1
                num2 = '8' + num2
                nl[i - 1] -= 1
        return [int(num1),int(num2)]
posted @ 2020-01-17 10:47  seyjs  阅读(240)  评论(0编辑  收藏  举报