leetcode–demo2两数相加
在做这条时一开始是想通过遍历链表得到两个数,然后将两数相加得到其和,最后取余得到每个数字并以此创建节点。可题目是有节点数要求的,1到100之间。若用此法就需要开大数。个人觉得没有必要,所以换了思路。
该思路就是每位相加,保存进位,让进位参与下一次计算中。
import java.util.Arrays;
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val){
this.val=val;
}
ListNode(int val,ListNode next){
this.val=val;
this.next=next;
}
public void add(ListNode node){
if (this.next==null){
this.next=node;
}else {
next.add(node);
}
}
public void show(){
ListNode temp=this;
while (temp!=null){
System.out.print(temp.val+"-");
temp=temp.next;
}
}
public static void main(String[] args) {
ListNode l1=new ListNode(0);
l1.add(new ListNode(2));
l1.add(new ListNode(4));
ListNode l2=new ListNode(0);
l2.add(new ListNode(1));
l2.add(new ListNode(2));
new Solution().addTwoNumbers(l1,l2).show();
}
}
class Solution{
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// ListNode temp=l1;
// int a=0;
// int b=0;
// int k=1;
// while (temp!=null){
// a+=temp.val*k;
// k*=10;
// temp=temp.next;
// }
// temp=l2;
// k=1;
// while (temp!=null){
// b+=temp.val*k;
// k*=10;
// temp=temp.next;
// }
// int c=a+b;
// ListNode l3=new ListNode(0);
// temp=l3;
// while (c>=1){
// temp.val=c%10;
// if(c/10>=1){
// temp.next=new ListNode(0);
// }
// temp=temp.next;
// c/=10;
// }
// return l3;
ListNode resultList=new ListNode(0);
ListNode p=l1,q=l2,cur=resultList;
int carry=0;//如果有进位则将carry重新赋值
while (p!=null||q!=null){
int a=(p!=null)?p.val:0;
int b=(q!=null)?q.val:0;
int sum=carry+a+b;
carry=sum/10;
cur.next=new ListNode(sum%10);
cur=cur.next;
if (p!=null){
p=p.next;
}
if (q!=null){
q=q.next;
}
}
//如果最后一位相加后有一个进位则单独计算
if (carry>0){
cur.next=new ListNode(carry);
}
return resultList.next;
}
}