LeetCode #1317 Convert Integer to the Sum of Two No-Zero Integers 將整數(shù)轉(zhuǎn)換為兩個(gè)無(wú)零整數(shù)的和

1317 Convert Integer to the Sum of Two No-Zero Integers 將整數(shù)轉(zhuǎn)換為兩個(gè)無(wú)零整數(shù)的和

Description:
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:

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

題目描述:
「無(wú)零整數(shù)」是十進(jìn)制表示中 不含任何 0 的正整數(shù)。

給你一個(gè)整數(shù) n,請(qǐng)你返回一個(gè) 由兩個(gè)整數(shù)組成的列表 [A, B],滿(mǎn)足:

A 和 B 都是無(wú)零整數(shù)
A + B = n
題目數(shù)據(jù)保證至少有一個(gè)有效的解決方案。

如果存在多個(gè)有效解決方案,你可以返回其中任意一個(gè)。

示例 :

示例 1:

輸入:n = 2
輸出:[1,1]
解釋?zhuān)篈 = 1, B = 1. A + B = n 并且 A 和 B 的十進(jìn)制表示形式都不包含任何 0 。

示例 2:

輸入:n = 11
輸出:[2,9]

示例 3:

輸入:n = 10000
輸出:[1,9999]

示例 4:

輸入:n = 69
輸出:[1,68]

示例 5:

輸入:n = 1010
輸出:[11,999]

提示:

2 <= n <= 10^4

思路:

雙指針遍歷, 查找到第一個(gè)不包含 0的整數(shù)就返回
時(shí)間復(fù)雜度O(nlgn), 空間復(fù)雜度O(1)

代碼:
C++:

class Solution 
{
public:
    vector<int> getNoZeroIntegers(int n) 
    {
        int i = 1, j = n - 1;
        while (true)
        {
            if (valid(i) && valid(j)) return {i, j};
            ++i;
            --j;
        }
    }
private:
    bool valid(int i)
    {
        while (i)
        {
            if (!(i % 10)) return false;
            i /= 10;
        }
        return true;
    }
};

Java:

class Solution {
    public int[] getNoZeroIntegers(int n) {
        int i = 1, j = n - 1;
        while (true) {
            if (valid(i) && valid(j)) return new int[]{i, j};
            i++;
            j--;
        }
    }
    
    private boolean valid(int i) {
        while (i != 0) {
            if (i % 10 == 0) return false;
            i /= 10;
        }
        return true;
    }
}

Python:

class Solution:
    def getNoZeroIntegers(self, n: int) -> List[int]:
        return next([i, n - i] for i in range(n) if '0' not in str(i) + str(n - i))
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容