题目描述:给定n位正整数a,去掉其中任意k个数字后,剩下的数字按原次序排列成一个新的正整数。
n (1<=n<=200)位的正整数a和k,k小于n。
先排序,再把大的数字删除,删掉k个即可。
public int deleteNumberAnother(int a, int k)
{
int aa = a; // 预先备份a的值
LinkedList<Integer> linkedList = new LinkedList<>();
int b = 0;
// 将每一位数字放入到链表中
while (a > 0)
{
b = a % 10; // 取个位数字
a /= 10;
linkedList.add(b);
}
// 对链表进行排序
Collections.sort(linkedList);
// 逐个删除数字
int len = 0;
while (k > 0)
{
len = linkedList.size();
linkedList.remove(len-1);
k--;
}
len = linkedList.size();
Iterator<Integer> it = linkedList.iterator();
Integer val = 0;
int res = 0;
// 从前向后计算最小新数
while (it.hasNext())
{
val = it.next();
val = (int)(val * Math.pow(10.0, --len));
res += val;
}
return res;
}
/**
* @param a n位的正整数
* @param k 删除的位数
*/
public int deleteNumber(int a, int k)
{
int index = 0;
String str = String.valueOf(a);
int len = str.length();
char[] s = str.toCharArray();
// 排序
Arrays.sort(s);
String newStr = new String(s);
for (index=len-1; index>=0 && k>0; index--, k--);
if (index < 0)
System.out.println("输入的k不合法!");
return Integer.parseInt(newStr.substring(0, index+1));
}