greatest integer

Mar 20, 2014 at 11:27am
hi everyone i would like to ask about a proper algo that i can use to solve this problem,i will try to write the code myself this is my own practice for an exam ..thx..
Each input starts with a positive integer N (≤ 50). In next lines there are N positive integers. Input is terminated by N = 0, which should not be processed.

For each input set, you have to print the largest possible integer which can be made by appending all the N integers.
input,
4
123 124 56 90
5
123 124 56 90 9
5
9 9 9 9 9
0
output
9056124123
99056124123
99999

Last edited on Mar 20, 2014 at 11:49am
Mar 20, 2014 at 12:41pm
you could try a greedy approach
simply sort them to highest to lowest

however, you'll define an especial comparison operator.
a<b <=> a+b < b+a
where + is the concatenation.
Mar 20, 2014 at 1:31pm
thank you for replying ...
now im using strings but it seems that the comparison is based on the length of the strings not their value then length (a+b)=length(b+a) then comparison can't get it done ...
can i have a sample code ? will try to see my mistake ...
thx...
Mar 20, 2014 at 3:03pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <vector>
#include <algorithm>
#include <iostream>

bool less(const std::string &a, const std::string &b){
	return a+b < b+a;
}

int main(){
	std::vector<std::string> values = {
		"123", "124", "56", "90", "9"
	};

	std::sort(values.rbegin(), values.rend(), less);
	for( auto x : values )
		std::cout << x;
	std::cout << '\n';
}


Last edited on Mar 20, 2014 at 3:07pm
Topic archived. No new replies allowed.