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))