题目描述

思路分析
这题最快最好的解法依然是对数组直接进行赋值操作,并在必要的情况下对数组扩容。
1、首先需要把K转为数组,这样方便一对一比对:
int count = 0;
int temp = K;
while (temp>0) {
temp=temp/10;
count++;
}
int[] B = new int[count];
temp = K;
while (temp>0) {
B[count-1] = temp%10;
temp = temp/10;
count--;
}
2、然后因为涉及到参数修正,我们先保证选定一个最长的数组。如果数组B长度大于A,则需要把A和B的引用做一交换:
if (A.length<B.length) {
int[] tem = A;
A = B;
B = tem;
}
3、接下来从A的末尾开始修正参数,设立临时参数temp保存进位,通过A和B的对应位置的值决定进位和修正值。
4、当判断A的第一位时,需要分A和B长度相等和长度不等两种情况考虑,再判断是否需要对数组A扩容。
5、若数组需要扩容,则把原A的参数逐个赋值到newA,再为newA的首位和次位赋值,最后A=newA,break。
代码实现
class Solution {
public List<Integer> addToArrayForm(int[] A, int K) {
int count = 0;
int temp = K;
while (temp>0) {
temp=temp/10;
count++;
}
int[] B = new int[count];
temp = K;
while (temp>0) {
B[count-1] = temp%10;
temp = temp/10;
count--;
}
if (A.length<B.length) {
int[] tem = A;
A = B;
B = tem;
}
int i = A.length-1;
int[] a = new int[A.length];
temp = 0;
while (i>=0) {
if (i==0) {
int sum = 0;
if (A.length == B.length) {
sum = A[0] + B[0] + temp;
}else {
sum = A[0] + temp;
}
if (sum >= 10) {
int[] newA = new int[A.length+1];
for(int x=A.length-1;x>0;x--) {
newA[x+1] = A[x];
}
newA[1] = sum%10;
newA[0] = sum/10;
A = newA;
break;
}else {
;
}
}
int sum;
if (B.length-A.length+i<0) {
sum = A[i] + temp;
}else {
sum = A[i] + B[B.length - A.length + i] + temp;
}
A[i] = sum%10;
temp = sum/10;
i--;
}
List<Integer> list = new ArrayList<>();
for(int j=0 ;j<A.length;j++) {
list.add(A[j]);
}
return list;
}
}
提交记录

说明这种数组修正的方式效率是很高的。
317

被折叠的 条评论
为什么被折叠?



