View Code of Problem 3917

import java.util.*;
public class Main {
	public static void main(String[] args) {
		Scanner in =new Scanner(System.in);
		int t =in.nextInt();
		for(int i =0;i<t;i++) {
			String n=in.next();
			char[] max = n.toCharArray();
			char[] min = n.toCharArray();
			int k =in.nextInt();
			int k2=k;
			for(int j =0;j<k;j++) {
				int maxloc=j;
				for(int l =max.length-1;l>=j;l--) {
					if(max[l]>max[maxloc]) {
						maxloc=l;
					}
				}
				if(maxloc==j) {
					k++;
					if(k>=max.length) {
						break;
					}
					continue;
				}
				char temp = max[j];
				max[j]=max[maxloc];
				max[maxloc]=temp;
			}
			for(int j =0;j<k2;j++) {
				int minloc=j;
				for(int l =min.length-1;l>=j;l--) {
					if(min[l]<min[minloc]) {
						if(j==0 && min[l]=='0') {
							continue;
						}
						minloc=l;
					}
				}
				if(minloc==j) {
					k2++;
					if(k2>=min.length) {
						break;
					}
					continue;
				}
				char temp = min[j];
				min[j]=min[minloc];
				min[minloc]=temp;
			}
			StringBuffer sbmax = new  StringBuffer();
			sbmax.append(max);
			StringBuffer sbmin = new  StringBuffer();
			sbmin.append(min);
			System.out.println(sbmin+" "+sbmax);
		}
	}
}

Double click to view unformatted code.


Back to problem 3917