组成最小的数
输入一个数字:
比如1432 然后输入一个数,比如为2,
那就等于要从1432中去除两个数字,使得去掉后的数是最小的~
比如去掉后就是:12 是最小的~求应该怎样做
[最优解释]
count <= 0) {
throw new RuntimeException("The count is out range [" + 1 + ", " + bits.length + "]");
}
List<Integer> allPosibility = new ArrayList<Integer>();
integers(bits, 0, 0, count, 0, allPosibility);
Collections.sort(allPosibility);
return allPosibility.get(0);
}
public static void integers(int[] bits, int startIndex,
int currentCount, int maxCount,
int posibility,
List<Integer> allPosibility) {
if (currentCount >= maxCount) {
allPosibility.add(posibility);
return;
}
for (int i = startIndex; i < bits.length; ++i) {
posibility = posibility * 10 + bits[i];
integers(bits, i + 1, currentCount + 1, maxCount, posibility, allPosibility);
posibility /= 10;
}
}
public static int[] bitsOfInteger(int n) {
List<Integer> temp = new ArrayList<Integer>();
do {
temp.add(n % 10);
n /= 10;
} while (n != 0);
int length = temp.size();
int[] result = new int[length];
for (int i = 0; i < length; ++i) {
result[i] = temp.get(length - 1 - i);
}
return result;
}
}
[其他解释]
写了个,不知道是否满足楼主要求。。。
public static void main(String[] args) {
String a = "1432";
int b = 2;
int resultLen = a.length() - b;
String result = "";
int[] array = new int[a.length()];
//转化成数组并排序
for(int k=0;k<a.length();k++){
array[k] = Integer.valueOf(a.charAt(k)) - 48;
}
Arrays.sort(array);
int j=0;
for(int i=0;i<resultLen;i++){
//第一位数组不以0开头
while(i==0 && array[j]==0){
j++;
}
result += array[j];
//每次处理完,截取a并重新排序,找到最小数
a = a.substring(a.indexOf(array[j]+"")+1);
for(int k=0;k<a.length();k++){
array[k] = Integer.valueOf(a.charAt(k)) - 48;
}
Arrays.sort(array);
j = 0 ;
}
System.out.println(result);
}
[其他解释]
把每个位上的数字取出来,放到数据里,排序,取前N个
[其他解释]
import java.util.*;
public class Hello {
public static void main(String[] args) {
System.out.println(minIntegers(1432, 2));
}
public static int minIntegers(int n, int count) {
int[] bits = bitsOfInteger(n);
if (count > bits.length
[其他解释]
还有一种方法
1. 取得各位数字,放在数组A
2. 排序结果存储在另一个数组B里,取前n位
3. 遍历这数组A,如果遍历到的数字在B中,则result = result * 10 + B[i],并从B中删除B[i],直到B为空import java.util.*;
public class Hello {
public static void main(String[] args) {
int n = 1402219;
int count = 3;
int[] A = bitsOfInteger(n);
if (count > A.length) {
throw new RuntimeException("Error.....");
}
int[] B = Arrays.copyOf(A, A.length);
Arrays.sort(B);
List<Integer> remain = new ArrayList<Integer>();
for (int i = 0; i < count; ++i) {
remain.add(B[i]);
}
int result = 0;
for (int i = 0; i < A.length; ++i) {
if (remain.contains(A[i])) {
result = result * 10 + A[i];
remain.remove(new Integer(A[i]));
}
}
System.out.println(result);
}
public static int[] bitsOfInteger(int n) {
List<Integer> temp = new ArrayList<Integer>();
do {
temp.add(n % 10);
n /= 10;
} while (n != 0);
int length = temp.size();
int[] result = new int[length];
for (int i = 0; i < length; ++i) {
result[i] = temp.get(length - 1 - i);
}
return result;
}
}
[其他解释]
不明白楼主说的不能排序,拿到的怎么就不能排序了?