给你一个字符串num和一个整数k。其中,num 表示一个很大的整数,字符中的每个字符依次对应整数上的各个数位
你可以交换这个整数相邻数位的数字 最多k次
请你返回你能得到的最小整数,并以字符串形式返回.
function trunNum(num,k){
let numArry = num.split('');
let nowIndex2 =0;
for (let j = 0; j < k; j++) {
// 偶对 241267--214267--124267--122467,奇连 321--231--213--123
if(numArry.length % 2 == 0){
let nowIndex = 0;
let K = numArry.length / 2 + (numArry.length / 2 -1),bas = (numArry.length / 2);
for (let i = 1; i <= K; i++) {
if(i<=bas){
if((numArry[nowIndex]>=numArry[nowIndex+1])){
let newNum = numArry[nowIndex],nextNum = numArry[nowIndex+1];
numArry[nowIndex] = nextNum;
numArry[nowIndex+1] = newNum;
nowIndex = i==bas?1:i+1;
break;
}else{
nowIndex = i==bas?1:i+1;
}
}else{
if((numArry[nowIndex]>=numArry[nowIndex+1])){
let newNum = numArry[nowIndex],nextNum = numArry[nowIndex+1];
numArry[nowIndex] = nextNum;
numArry[nowIndex+1] = newNum;
nowIndex = K==i?0:(i-bas)*2+1;
break;
}else{
nowIndex = K==i?0:(i-bas)*2+1;
}
}
}
}else{
for (let i = nowIndex2; i < numArry.length; i++) {
if(numArry[i]<=numArry[i+1]&&i==numArry.length-2){
i=0;
nowIndex2 = 0;
}
if((numArry[i]>=numArry[i+1])){
let newNum = numArry[i],nextNum = numArry[i+1];
numArry[i] = nextNum;
numArry[i+1] = newNum;
nowIndex2 = i==numArry.length-1?0:i+1;
break;
}else{
nowIndex2 = i==numArry.length-1?0:i+1;
}
}
}
}
return numArry.join("");
}
想法几分钟,编程几小时!
0 个评论
要回复文章请先登录或注册