leetcode 2 Add Two Numbers

来源:互联网 发布:阴上买入指标公式源码 编辑:程序博客网 时间:2024/06/06 14:01
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.
Output: 7 -> 0 -> 8


Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {      ListNode head1 = l1;ListNode head2 = l2;ListNode l3 = new ListNode(0);ListNode head3 = l3;int ad = 0;while(head1 != null || head2 != null){int a = 0;if(head1 != null){a = head1.val;head1 = head1.next;}int b = 0;if(head2 != null){b = head2.val;head2 = head2.next;}a = a + b + ad;head3.next = new ListNode(a%10);head3 = head3.next;ad = a / 10;}if(ad == 1){head3.next = new ListNode(1);}return l3.next;//return l1;    }}


0 0
原创粉丝点击