-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_1694_reformatNumber.cc
78 lines (71 loc) · 1.4 KB
/
Problem_1694_reformatNumber.cc
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
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include <string>
#include "UnitTest.h"
using namespace std;
class Solution
{
public:
string getDigits(string str)
{
string ans;
for (int i = 0; i < str.length(); i++)
{
if (str[i] != ' ' && str[i] != '-')
{
ans.push_back(str[i]);
}
}
return ans;
}
string reformatNumber(string number)
{
string digits = getDigits(number);
string ans;
int N = digits.length();
bool diff = N % 3 == 1 ? true : false;
for (int i = 0; i < N; i++)
{
if (i != 0 && i % 3 == 0)
{
// 除0位置,每3个字符加-
ans.push_back('-');
}
if (diff && N - i == 4)
{
// 特殊情况
ans += digits.substr(N - 4, 2) + "-" + digits.substr(N - 2, 2);
break;
}
ans.push_back(digits[i]);
}
return ans;
}
};
bool isEqualString(string s1, string s2)
{
if (s1.length() != s2.length())
{
return false;
}
for (int i = 0; i < s1.length(); i++)
{
if (s1[i] != s2[i])
{
return false;
}
}
return true;
}
void testReformatNumber()
{
Solution s;
EXPECT_TRUE(isEqualString("123-456", s.reformatNumber("1 - 23 - 45 6")));
EXPECT_TRUE(isEqualString("123-45-67", s.reformatNumber("123 4-567")));
EXPECT_TRUE(isEqualString("123-456-78", s.reformatNumber("123 4-5678")));
EXPECT_SUMMARY;
}
int main()
{
testReformatNumber();
return 0;
}