zoukankan      html  css  js  c++  java
  •  【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)]
  • 相关阅读:
    Silverlight DataGrid 获取 Row 左键双击事件
    数据结果集拼接到一行
    程序“[6040] iisexpress.exe”已退出,返回值为 0 (0x0)。
    新手用WPF山寨QQ管家7.6(二)
    风向十六方位图和温度湿度图
    新手向使用XAML画出Win8风格图标的照相机,小姐你相机~~
    新手用WPF山寨QQ管家7.6(一)
    实验一
    实验5
    实验4
  • 原文地址:https://www.cnblogs.com/seyjs/p/12204682.html
Copyright © 2011-2022 走看看