我想在parenteses中打印一个重复数字的数组,不知道怎么做?
数组:
{2,4,5,5,5,7,1,1,4}
我需要将其打印为:
24(555)7(11)4
这是我的伪代码:
boolean inRun = false;
for loop;
if (inRun);
if values[i] != the preceding value, print ")";
inRun = false;
if(!inRun)
if values[i] = the following value, print "("
inRun = true;
System.out.print([i])
if inRun, print ")"
答案 0 :(得分:1)
import java.util.Arrays;
public class Test{
public static void main(String[] args){
int arr[] = new int[5];
arr[0] = 5;
arr[1] = 3;
arr[2] = 2;
arr[3] = 2;
arr[4] = 3;
Arrays.sort(arr);
System.out.print("(" + arr[0]);
for (int i=1; i<arr.length;i++) {
if(arr[i] == arr[i-1]) {
System.out.print(arr[i]);
}
else {
System.out.print(")(" + arr[i]);
}
}
System.out.print(")");
}
}
输出:(22)(33)(5)
答案 1 :(得分:0)
你走了:
int arr[] = {2,4,5,5,5,7,1,1,4,4};
StringBuilder sb = new StringBuilder();
boolean repeat = false;
for (int i=0; i<arr.length; i++) {
if (!repeat && (i+1) < arr.length && arr[i] == arr[i+1]) {
sb.append('(');
repeat = true;
}
sb.append(arr[i]);
if (repeat && (i+1) < arr.length && arr[i] != arr[i+1]) {
sb.append(')');
repeat = false;
}
if (repeat && i == arr.length-1)
sb.append(')');
}
// prints 24(555)7(11)(44)
System.out.println(sb);