Add Two Numbers
Last updated
Was this helpful?
Last updated
Was this helpful?
/*
本算法答案由上岸科技提供。
上岸科技是一个专致力于高效培养北美留学生拥有实际面试能力的团体。
我们采用小班化线上,线下教学让学生更快,更好的学习到想要的知识。
团队主要由一群怀揣情怀于美国高校毕业的一线IT公司工程师构成。
我们坚信对于求职者算法并不是全部,合理的技巧加上适当的算法培训能够大大的提升求职成功概率也能大大减少刷题的痛苦。
正如我们的信仰:我们教的是如何上岸而不仅是算法。
更多信息请关注官网:https://www.shanganonline.com/
*/
/**
* 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 dummy = new ListNode(-1);
ListNode temp = dummy;
ListNode t1 = l1;
ListNode t2 = l2;
int carry = 0;
while(t1 != null || t2 != null){
int val1 = t1 == null ? 0 : t1.val;
int val2 = t2 == null ? 0 : t2.val;
int sum = carry + val1 + val2;
carry = sum / 10;
sum = sum % 10;
ListNode newNode = new ListNode(sum);
temp.next = newNode;
temp = newNode;
if(t1 != null) t1 = t1.next;
if(t2 != null) t2 = t2.next;
}
if(carry != 0){
ListNode newNode = new ListNode(carry);
temp.next = newNode;
temp = newNode;
}
return dummy.next;
}
}