解題思路
先驗證四段十進位格式,再依首段分類。
以句點切成恰四段,各段不得空白,且每個字元只能是ASCII數字,數值必須0至255。
格式錯誤一律N;否則依第一段的歷史題目區間查A、B、C、D、E。
未列入的合法首段如0、127或248至255,輸出X,不能套用現代網路配置補上其他判斷。
時間 O(L),空間 O(L),L為字串長度。
Step-by-step animation
公開範例223.255.255.1
步驟 1 / 3
步驟 1
輸入223.255.255.1,切成四段。
223
255
255
1
- 步驟
- 1
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
string s;
getline(cin, s);
vector<int> a;
int v = 0, len = 0;
bool ok = true;
for (char c : s + ".") {
if (c == '.') {
if (!len)
ok = false;
a.push_back(v);
v = len = 0;
} else if (c >= '0' && c <= '9') {
len++;
v = min(256, v * 10 + c - '0');
if (v > 255)
ok = false;
} else
ok = false;
}
if (!ok || a.size() != 4) {
cout << "N\n";
return 0;
}
int x = a[0];
cout << (x >= 1 && x <= 126 ? 'A'
: x >= 128 && x <= 191 ? 'B'
: x >= 192 && x <= 223 ? 'C'
: x >= 224 && x <= 239 ? 'D'
: x >= 240 && x <= 247 ? 'E'
: 'X')
<< '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。