野猪小李刷leecode-02两数相加
不学无术大龄小白一枚,leecode上的第二题两数相加,自己的实现思路,欢迎各位前辈和后起之秀指导讨论!内联代码片
。
题目:
提示如下每台实现提示:
函数实现(没按照leecode给出的格式编写,习惯性写了个多态就不改了)。
public List<Integer> sumturn(List<Integer> list1 ,List<Integer> list2){
//最终接收结果的链表
List<Integer> linkedList=new LinkedList<Integer>();
//数的位数
int listLen1=list1.size();
int listLen2=list2.size();
//得到最大位数,确定循环长度
int maxlen=listLen1>listLen2?listLen1:listLen2;
//用于接收最大数字的链表
List<Integer> maxlinkedList=new LinkedList<Integer>();
maxlinkedList=listLen1>listLen2?list1:list2;
//得到最小位数用于确定进入哪个选择分支
int minlen=listLen1<listLen2?listLen1:listLen2;
//进位
int carry=0;
//当前位置数字
int nowLocationnum=0;
//按照最长的
for (int i = 0; i < maxlen; i++) {
if (minlen-i>0) {
nowLocationnum = (list1.get(i) + list2.get(i) + carry)%10;
carry =(list1.get(i) + list2.get(i) + carry)/ 10;
linkedList.add(nowLocationnum);
if (carry==1&&maxlen-i==0){//最后一位还有进位的情况下
linkedList.add(i+1,carry);
}
} else {
nowLocationnum=(maxlinkedList.get(i)+carry)%10;
carry=(maxlinkedList.get(i)+carry) /10;
linkedList.add(nowLocationnum);
if (carry==1&&maxlen-i-1==0){
linkedList.add(carry);
}
}
}
return linkedList;
}
在主函数调用方法,用leecode给出的数据测试
leecode02 linkedlist = new leecode02();
List<Integer> list1 = new LinkedList<Integer>(Arrays.asList(2, 4, 3));
List<Integer> list2 = new LinkedList<Integer>(Arrays.asList(5, 6, 4));
List<Integer> list3 = new LinkedList<Integer>(Arrays.asList(0));
List<Integer> list4 = new LinkedList<Integer>(Arrays.asList(0));
List<Integer> list5 = new LinkedList<Integer>(Arrays.asList(9, 9, 9, 9, 9, 9, 9));
List<Integer> list6 = new LinkedList<Integer>(Arrays.asList(9, 9, 9, 9));
List<Integer> sumturn = linkedlist.sumturn(list1, list2);
System.out.println(sumturn);
List<Integer> sumturn2 = linkedlist.sumturn(list3, list4);
System.out.println(sumturn2);
List<Integer> sumturn3 = linkedlist.sumturn(list5, list6);
System.out.println(sumturn3);