美文网首页
leetcode2-Add Two Numbers

leetcode2-Add Two Numbers

作者: miky_zheng | 来源:发表于2019-02-19 17:52 被阅读0次

    问题:

    You are given two non-empty linked lists representing two non-negative integers. 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.
    
    You may assume the two numbers do not contain any leading zero, except the number 0 itself.
    
    Example:
    
    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 0 -> 8
    Explanation: 342 + 465 = 807.
    

    解法:

    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode ln1 = l1, ln2 = l2, head = null, node = null;
            int carry = 0, remainder = 0, sum = 0;
            head = node = new ListNode(0);
            
            while(ln1 != null || ln2 != null || carry != 0) {
                sum = (ln1 != null ? ln1.val : 0) + (ln2 != null ? ln2.val : 0) + carry;
                carry = sum / 10;
                remainder = sum % 10;
                node = node.next = new ListNode(remainder);
                ln1 = (ln1 != null ? ln1.next : null);
                ln2 = (ln2 != null ? ln2.next : null);
            }
            return head.next;
        }
    }
    

    相关文章

      网友评论

          本文标题:leetcode2-Add Two Numbers

          本文链接:https://www.haomeiwen.com/subject/hfbfyqtx.html