[C++]判断最大字符串
2016-04-11 22:15
399 查看
判断最大字符串
题目描述如下:
Giving N numbers, try to use them to construct a max number.For example, there are three numbers 56 54 5, you can make numbers 56545, 56554, 54565, 54556, 55654, 55456. The answer is the max number 56554. It is guranteed that all numbers are positive integers and less than 1000.
There is only two lines in Input.
First line is a integer N which means that there are N positive integers.
Second lines are N positive integers.
Sample Inputs
3
56 54 5
Sample Output
56554
#include <iostream> #include <vector> #include <algorithm> #include <numeric> using namespace std; bool compare_bewteen_strings(string a, string b) { for (int j = 0; j != b.length(); j++) { if (b[j] > a[j]) { return false; } if (b[j] < a[j]) { return true; } } int i = 0; while (b[b.length() - 1] == a[b.length() + i]) { if (b.length() + i == a.length()) { return true; } else { if (b[b.length() - 1] > a[b.length() + i]) { return false; } else if (b[b.length() - 1] < a[b.length() + i]) { return true; } } i++; } if (b[b.length() - 1] > a[b.length()]) { return false; } else { return true; } } bool special_cmp(string a, string b) { if (a.length() > b.length()) { return compare_bewteen_strings(a, b); } if (b.length() > a.length()) { return (!compare_bewteen_strings(b, a)); } if (a.length() == b.length()) { for (int i = 0; i != a.length(); i++) { if (a[i] > b[i]) { return true; } if (a[i] < b[i]) { return false; } } } return true; } int main() { vector<string> test; int n; cin >> n; string temp; for (int i = 0; i != n; i++) { cin >> temp; test.push_back(temp); } sort(test.begin(), test.end(), special_cmp); for (vector<string>::iterator iter = test.begin(); iter != test.end(); iter++) { cout << *iter; } cout << endl; return 0; }
答案用的是相邻两个字符串相加,判断谁加谁更大。(相当精妙。)
#include <iostream> #include <algorithm> #include <string> #include <vector> using std::cin; using std::cout; using std::sort; using std::endl; using std::string; using std::vector; bool cmp(string a, string b) { return a+b > b+a; } int main() { int N; string tmp; vector<string> max; vector<string>::iterator iter; cin >> N; while (N--) { cin >> tmp; max.push_back(tmp); } sort(max.begin(), max.end(), cmp); if (!max.empty()) { for (iter = max.begin(); iter != max.end(); ++iter) { cout << *iter; } cout << endl; } return 0; }
相关文章推荐
- 我也不知道他是第几次c++作业——代码篇
- C语言输出打印乘法口诀表
- C\C++ sizeof 陷阱&&总结
- C++实验3—定期存款利息计算器
- 常用C/C++开发环境【待补充】
- C++走向远洋——33(静态成员的应用)
- C++作业3
- [c++] C++11 Signals and Slots
- c++第三次实验
- C语言基础篇(2):按位比较是否相等、找出不是成对出现的单数、不用中间变量实现两个数的交换
- c++第三次上机实验-个人所得税计算器
- c语言中的字节数关系、
- 浅谈C++容器(六)
- 浅谈C++容器(二)
- 浅谈C++容器(一)
- 第3周 C语言及程序设计初步例程-47 小小型应用系统开发指导(二)
- C++第3次作业
- C++问题小结--1.命名空间namespace应用举例
- C++实验3-多分数段函数求值
- 【c++】挑7