滴滴笔试求解
import java.util.*; public class Main9 { public static void sort(ArrayList<Integer> l,int low,int high){ int n=high-low+1; //几个数字 int temp; for(int i=0;i<n-1;i++){ for(int j=low;j<=high-i-1;j++){ if(l.get(j).intValue()>l.get(j+1).intValue()){ //? temp=l.get(j); l.set(j,l.get(j+1)); l.set(j+1,temp); } } } } public static void main(String[] args) { // TODO Auto-generated method stub Scanner in=new Scanner(System.in); while(in.hasNext()) { int n=in.nextInt(); if(n==1) { System.out.print(in.next()); return; } ArrayList<Integer> shuzi=new ArrayList<>(); ArrayList<String> fuhao=new ArrayList<>(); ArrayList<Boolean> canSwap=new ArrayList<>(); //符号两边数是否可以交换 int index=1; for(int i=0;i<n;i++){ shuzi.add(Integer.parseInt(in.next())); if(i<n-1){ fuhao.add(in.next()); } } // System.out.println(shuzi); // System.out.println(fuhao); for(int i=0;i<n-1;i++) { canSwap.add(false); } //初始化canSwap for(int i=0;i<n-1;i++) { String now=fuhao.get(i); if(now.equals("+")) { if(i==0) { if(i+1<=n-2) { //下一个符号存在 String next=fuhao.get(i+1); if(now.equals("+")||now.equals("-")) { canSwap.set(i, true); } }else { canSwap.set(i, true); } }else { String before=fuhao.get(i-1); if(before.equals("+")) { //前一个符号为加号 if(i+1<=n-2) { //下一个符号存在 String next=fuhao.get(i+1); if(next.equals("+")||next.equals("-")) { canSwap.set(i, true); } }else { canSwap.set(i, true); } } } }else if(now.equals("*")) { if(i==0) { canSwap.set(i, true); }else { String before=fuhao.get(i-1); if(!before.equals("/")) { canSwap.set(i, true); } } } } // System.out.println(canSwap); int flag=0; int low=0; int high=0; for(int i=0;i<n-1;i++) { boolean can=canSwap.get(i).booleanValue(); if(can) { if(flag==0) { low=i; flag=1; } if(i==n-2) { high=n-1; sort(shuzi,low,high); // System.out.println(shuzi); } }else { if(flag==1) { flag=0; high=i; // System.out.println(low+" "+high); sort(shuzi,low,high); // System.out.println(shuzi); } } } for(int i=0;i<n-1;i++){ System.out.print(shuzi.get(i)+" "+fuhao.get(i)+" "); } System.out.print(shuzi.get(n-1)); } } }
#滴滴##笔试题目#