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
79
80
81
| #include <iostream>
#include "console.h"
#include "SimpleTest.h"
#include "string.h"
#include "vector.h"
using namespace std;
int widthOfNum(int num){
if (num == 0) return 1; // 0是1位数
int count = 0;
// 处理负数:转换为正数
if (num < 0) {
num = -num;
++count;
}
while (num > 0) {
count++;
num /= 10;
}
return count;
}
int maxWidthOfVector(Vector<int> &v){
int numVec = v.size();
int maxNum = widthOfNum(v[0]);
for(int i= 1;i<numVec;i++){
if(widthOfNum(v[i]) > maxNum)
{maxNum = widthOfNum(v[i]);}
}
return maxNum;
}
void printVectorAdvanced(Vector<int> &v)
{
//runSimpleTests(SELECTED_TESTS);
int maxVecWidth = maxWidthOfVector(v)+2;
string s1,s2,s3;
int count = 0;
for(int i:v)
{
int iWidth = widthOfNum(i);
s1 += string("+") + string(maxVecWidth,'-');
int whiteSpace1 = (maxVecWidth-iWidth)/2;
int whiteSpace2 = maxVecWidth - whiteSpace1-iWidth;
s2 += string("|") + string(whiteSpace1,' ') + to_string(i) + string(whiteSpace2,' ');
int whiteSpace3 = (maxVecWidth+1)/2;
s3 += string(whiteSpace3,' ') + to_string(count) + string(maxVecWidth/2,' ');
count++;
}
s1 += string("+");
s2 += string("|");
cout << s1 << "\n" << s2 << "\n" << s1 << "\n" << s3 << endl;
}
STUDENT_TEST("测试maxWidthOfVector函数")
{
Vector<int> v1 = {43,1,9,129,5821,3};
Vector<int> v2 = {43,1,9,129,582,3,-256};
EXPECT_EQUAL(maxWidthOfVector(v1), 4);
EXPECT_EQUAL(maxWidthOfVector(v2), 7);
}
STUDENT_TEST("测试函数widthOfNum"){
EXPECT_EQUAL(widthOfNum(1890),4);
EXPECT_EQUAL(widthOfNum(0),1);
EXPECT_EQUAL(widthOfNum(-1),2);
}
int main()
{
//runSimpleTests(SELECTED_TESTS);
Vector<int> v1 = {43,1,9,129,5821,3};
Vector<int> v2 = {43,1,9,129,5821,3,-5633};
printVectorAdvanced(v2);
return 0;
}
|