首页 > 代码库 > leetcode Add Two Numbers
leetcode Add Two Numbers
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * }10 * }11 */12 public class Solution {13 public ListNode addTwoNumbers(ListNode l1, ListNode l2) {14 ListNode temp1,temp2;15 temp1=l1;16 temp2=l2;17 int flag=0;18 int sum=0,v1=0,v2=0;19 ListNode res=new ListNode(-1);20 ListNode curr=res;21 while (temp1!=null || temp2!=null) {22 if (temp1==null) {23 v1=0;24 }else {25 v1=temp1.val;26 }27 if (temp2==null) {28 v2=0;29 }else {30 v2=temp2.val;31 }32 sum=v1+v2+flag;33 if (sum>=10) {34 sum=sum-10;35 flag=1;36 }else {37 flag=0;38 }39 ListNode node=new ListNode(sum);40 curr.next=node;41 curr=curr.next;42 if (temp1!=null) {43 temp1=temp1.next;44 }45 if (temp2!=null) {46 temp2=temp2.next;47 }48 }49 if (flag>0) {50 curr.next=new ListNode(1);51 }52 return res.next;53 }54 }
leetcode Add Two Numbers
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。