解题图解:
下面是代码:
cpp
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* addToArrayForm(int* num, int numSize, int k, int* returnSize){
int k_tem =k;
int klen=0;
while(k_tem){//看看k有几位
k_tem /=10;
klen++;
}
int len = numSize>klen?numSize:klen;
int *arry =(int*)malloc(sizeof(int)*(len+1));
int num_end=numSize-1;
int number_in=0;
for(int i=0;i<len;i++){
int a=0;
if(num_end>=0){//k的位数比提供的数组大的情况
a=num[num_end];
}
int bit_number=a+k%10+number_in;
k/=10;
number_in=0;
if(bit_number>=10){
arry[i]=bit_number-10;
number_in=1;
}else{
arry[i]=bit_number;
}
num_end--;
}
int flag=0;//用于判断开辟的数组最后是len,还是len+1
if(number_in==1){//如果最后一位需要进位就让开辟好的数组最后一位置为1
arry[len]=1;
flag=1;
}
int arry_end=(flag==1?len:len-1);
int arry_start=0;
while(arry_start<arry_end){
//不用临时变量交换数组,可以学一下
arry[arry_start]=arry[arry_start]^arry[arry_end];
arry[arry_end]=arry[arry_start]^arry[arry_end];
arry[arry_start]=arry[arry_start]^arry[arry_end];
arry_end--;
arry_start++;
}
*returnSize=(flag==1?len+1:len);
return arry;
}