网上看到一道笔试题,觉的还算能实现,没想到还是把简单题目的写繁琐了。
/**
* 题目:给定一个数组A,里面只出现0-9这10个数字,但不一定全部出现,
* 然后给定一个K的值,求A中大于K的整数当中最小的一个,并输出。
* 例如A={0,1}, k =12,则结果为100.
*
* 这里采用回溯处理,这里只实现了当K为正整数的解法。
*/
#include <iostream>
#include <string>
const int DIGITCOUNT = 10;
void getExist(std::string num, int* existNum);
int getMinAns(int orgval, std::string num);
int main(){
std::string numstr;
int orgval;
while(std::cin>>orgval>>numstr){
int ans = getMinAns(orgval, numstr);
std::cout<<ans<<std::endl;
}
}
void getExist(std::string num, int* existNum){
int i, len = num.length();
memset(existNum, 0, sizeof(int)*DIGITCOUNT);
for(i = 0; i < len; i++){
if(num[i]>='0' && num[i]<='9'){
existNum[num[i]-'0'] = 1;
}
}
}
int getMinAns(int orgval, std::string num){
//assert(orgval >= 0);
int existNum[DIGITCOUNT];
getExist(num, existNum);
int digit_len = 0, tmp = orgval;
do{
digit_len++;
tmp /= 10;
}while(tmp);
int* org = new int [digit_len];
int* ans = new int [digit_len];
tmp = orgval; int i, k;
for(i = digit_len-1; i >= 0; i--){
org[i] = tmp%10;
tmp /= 10;
}
int minval = 0;
while(!existNum[minval]){ minval++;}
int isBig = 0; //0 represent equal, 1 represent big, -1 represent get back
for(i = 0; i < digit_len; i++){
if(i == -1) break;
if(isBig == 1){
ans[i] = minval;
}
else if(isBig == 0 && existNum[org[i]] && i != digit_len-1){
ans[i] = org[i];
}
else{
for(k = org[i]+1; k<DIGITCOUNT && !existNum[k]; k++);
if(k<DIGITCOUNT){
ans[i] = k;
isBig = 1;
}
else{
i -= 2;
isBig = -1;
}
}
}
int ansval = 0;
if(i != -1){
for(k = 0; k < digit_len; k++){
ansval = ansval*10 + ans[k];
}
}
else{
if(minval>0){
ansval = minval;
}
else{
while(!existNum[++ansval]){/*void*/};
}
for(k = 0; k <digit_len; k++){
ansval = ansval*10 + minval;
}
}
return ansval;
}