/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode nhead=new ListNode(-1);
ListNode curr=nhead;
int jinwei=0;
ListNode first=l1;
ListNode second=l2;
while(first!=null || second!=null){
int a=0,b=0;
if(first!=null){
a=first.val;
first=first.next;
}
if(second!=null){
b=second.val;
second=second.next;
}
int sum=a+b+jinwei;
jinwei=sum/10;
curr.next=new ListNode(sum%10);
curr=curr.next;
}
if(jinwei>0){
curr.next=new ListNode(jinwei);
}
return nhead.next;
}
}
Leetcode2兩數相加
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.