The code copy is as follows:
import java.util.LinkedList;
public class OJ {
public OJ() {
super();
}
/*
* Function: Enter a line of numbers. If we regard '5' in this line of numbers as spaces, we will get a line of non-negative integers separated by spaces (some integers may start with '0', and the '0' of these headers 'It should be ignored
* , unless this integer is composed of several '0's, then this integer is 0). These non-negative integers are sorted in order from large to small.
*
* Input: input, a string composed of 0~9 numbers.
* Input data requirements: nothing more than numeric characters, length greater than 0 and not greater than 1000, the separated non-negative integer will not be greater than 10000000, and the input data cannot be composed entirely of '5'.
*
* Output: output, string, is the separated non-negative integer sorting result (from large to small), and adjacent integers are separated by a space, and there are no spaces before the first integer and after the last integer.
*
* Return: Return 0 normally, return -1 if the exception fails.
*/
public static int getSortNum(final String input, final StringBuilder output) {
if(input.length()<=0 || input.length() > 1000){
return -1;
}
String[] nums = input.split("5");
int len = nums.length;
LinkedList<Integer> sorted = new LinkedList<Integer>();
int j = 0;
for (int i = 0; i < len; i++) {
int temp = 0;
int k = j;
if (!nums[i].equals("")) {
try {
temp = Integer.valueOf(nums[i]);
if(temp > 100000000){
return -1;
}
if (sorted.isEmpty()) {
sorted.addFirst(temp);
j++;
} else {
while (k > 0 && (temp > sorted.get(k - 1))) {
k--;
}
sorted.add(k, temp);
j++;
}
} catch (Exception ex) {
return -1;
}
}
}
for (int i = 0; i < sorted.size() - 1; i++) {
output.append(sorted.get(i) + " ");
}
output.append(sorted.getLast());
output.trimToSize();
return 0;
}
}
Test cases:
The code copy is as follows:
import junit.framework.Assert;
import junit.framework.TestCase;
public class OJTest extends TestCase
{
public void testCase01()
{
// Write a test case here
final StringBuilder output = new StringBuilder();
Assert.assertTrue(-1 == OJ.getSortNum("1234543 215555", output));
}
public void testCase02()
{
final StringBuilder output = new StringBuilder();
Assert.assertTrue(0 == OJ.getSortNum("1234543215555", output) && "4321 1234".equals(output.toString()));
}
public void testCase03()
{
final StringBuilder output = new StringBuilder();
Assert.assertTrue(0 == OJ.getSortNum("12345432155556436567", output) && "6436 4321 1234 67".equals(output.toString()));
}
public void testCase04()
{
final StringBuilder output = new StringBuilder();
Assert.assertTrue(0 == OJ.getSortNum("12345432155500000000000056436567", output) && "6436 4321 1234 67 0".equals(output.toString()));
}
public void testCase05()
{
final StringBuilder output = new StringBuilder();
Assert.assertTrue(-1 == OJ.getSortNum("1234543215510000000000000000001556436567", output));
}
}