Skip to content

Commit 3e82d22

Browse files
committed
Add: Add 2025/9/8
1 parent 1d4c52f commit 3e82d22

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
# 1317. Convert Integer to the Sum of Two No-Zero Integers
2+
3+
No-Zero integer is a positive integer that does not contain any `0` in its decimal representation.
4+
5+
Given an integer `n`, return a list of two integers `[a, b]` where:
6+
7+
- `a` and `b` are No-Zero integers.
8+
- `a + b = n`
9+
10+
The test cases are generated so that there is at least one valid solution.
11+
If there are many valid solutions, you can return any of them.
12+
13+
**Constraints:**
14+
15+
- `2 <= n <= 10^4`
16+
17+
## 基礎思路
18+
19+
題目希望將一個正整數 `n` 拆成兩個不含 `0` 的整數 `a``b`,且滿足 $a + b = n$。
20+
我們可以觀察出這是一個構造題,只要找到**任意一組**合法的 `a``b` 即可,不需要找出所有組合或最佳答案。
21+
22+
考慮以下策略:
23+
24+
-`1` 開始遍歷所有可能的 `a` 值,對應的 `b = n - a`
25+
- 檢查 `a``b` 是否皆不含數字 `0`
26+
- 第一組符合條件的即為解,立即回傳。
27+
28+
這樣的暴力策略在本題是可行的,原因是:
29+
30+
- `n` 最大為 $10^4$,最多嘗試 $n-1$ 次,效能可接受。
31+
- 題目保證至少存在一組合法解,因此一定可以提早停止。
32+
33+
## 解題步驟
34+
35+
### Step 1: 嘗試所有可能拆法並回傳第一組合法結果
36+
37+
使用 `for` 迴圈從 `1` 遍歷到 `n - 1`,並檢查是否 `a``b` 都是不含 0 的整數。
38+
39+
- 利用 `toString().includes("0")` 判斷是否含有 `0`
40+
- 一旦找到符合條件的組合即回傳 `[a, b]`
41+
42+
```typescript
43+
for (let firstCandidate = 1; firstCandidate < n; firstCandidate++) {
44+
const secondCandidate = n - firstCandidate;
45+
if (!firstCandidate.toString().includes("0") && !secondCandidate.toString().includes("0")) {
46+
return [firstCandidate, secondCandidate];
47+
}
48+
}
49+
```
50+
51+
### Step 2: 回傳空陣列(理論上不會發生)
52+
53+
由於題目保證一定有解,此行純粹作為保險機制存在。
54+
55+
```typescript
56+
return [];
57+
```
58+
59+
## 時間複雜度
60+
61+
- 最多嘗試 $n - 1$ 種可能,每種需轉字串並檢查是否含 `0`
62+
- 每次檢查約需 $O(\log n)$ 時間。
63+
- 總時間複雜度為 $O(n \log n)$。
64+
65+
> $O(n \log n)$
66+
67+
## 空間複雜度
68+
69+
- 僅使用常數額外空間(少量變數與字串操作)。
70+
- 總空間複雜度為 $O(1)$。
71+
72+
> $O(1)$
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
function getNoZeroIntegers(n: number): number[] {
2+
for (let firstCandidate = 1; firstCandidate < n; firstCandidate++) {
3+
const secondCandidate = n - firstCandidate;
4+
if (!firstCandidate.toString().includes("0") && !secondCandidate.toString().includes("0")) {
5+
return [firstCandidate, secondCandidate];
6+
}
7+
}
8+
return [];
9+
}

0 commit comments

Comments
 (0)