时间轴

2025-09-23

init


题目:


这题比较简单,不过还是注意下 stringstream 的用法吧

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <sstream>
#include <stdio.h>
#include <string>
#include <vector>
using std::string;
using std::stringstream;
using std::vector;

class Solution {
public:
int compareVersion(string version1, string version2) {
int n, i;
int v1, v2;
int revision_number;
string revision_number_str;
vector<int> vec1, vec2;
stringstream ss(version1);

while (std::getline(ss, revision_number_str, '.')) {
try {
revision_number = std::stoi(revision_number_str);
} catch (std::exception e) {
printf("illegal input: %s\n", e.what());
exit(-1);
}
vec1.push_back(revision_number);
}

// 覆盖缓冲区内容
ss.str(version2);
// 重置状态位
ss.clear();
while (std::getline(ss, revision_number_str, '.')) {
try {
revision_number = std::stoi(revision_number_str);
} catch (std::exception e) {
printf("Illegal input: %s\n", e.what());
exit(-1);
}
vec2.push_back(revision_number);
}
n = vec1.size() > vec2.size() ? vec1.size() : vec2.size();

for (i = 0; i < n; i++) {
// 赋值
if (i < vec1.size())
v1 = vec1[i];
else
v1 = 0;
if (i < vec2.size())
v2 = vec2[i];
else
v2 = 0;

if (v1 < v2) {
return -1;
} else if (v1 > v2) {
return 1;
} else {
continue;
}
}
return 0;
}
};