Skip to content

Commit 1b2da06

Browse files
authored
Create min_num.cpp
1 parent abb1ba2 commit 1b2da06

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

0000.jian_zhi_offer/45/min_num.cpp

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
class Solution
2+
{
3+
public:
4+
bool compareAndSwap(std::string& str1, std::string& str2)
5+
{
6+
auto numstr1 = str1 + str2;
7+
auto numstr2 = str2 + str1;
8+
long num1 = std::stol(numstr1);
9+
long num2 = std::stol(numstr2);
10+
if (num1 > num2)
11+
{
12+
str1.swap(str2);
13+
return true;
14+
}
15+
return false;
16+
}
17+
string minNumber(vector<int>& nums)
18+
{
19+
vector<std::string> numsStr(nums.size());
20+
int size = 0;
21+
for (int i=0;i<nums.size();i++)
22+
{
23+
numsStr[i] = std::to_string(nums[i]);
24+
size += numsStr[i].size();
25+
}
26+
for (int i = 0;i < numsStr.size()-1;i++)
27+
{
28+
for (int j = i + 1;j > 0;j--)
29+
{
30+
if (!compareAndSwap( numsStr[j-1], numsStr[j]))
31+
break;
32+
}
33+
}
34+
std::string rst;
35+
rst.resize(size+5);
36+
rst.clear();
37+
for (int i = 0;i < numsStr.size();i++)
38+
{
39+
rst += numsStr[i];
40+
}
41+
return rst;
42+
}
43+
};

0 commit comments

Comments
 (0)