码迷,mamicode.com
首页 > 其他好文 > 详细

2. Add Two Numbers

时间:2015-04-15 12:53:30      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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

题解:

单链表的操作,要注意链表为空时的判断

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1 == null)
            return l2;
        if(l2 == null)
            return l1;
        ListNode result = new ListNode(-1);
        ListNode node = result;
        int carry = 0;
        
        while(l1 != null || l2 != null){
            int val1 = l1 == null ? 0 : l1.val;
            int val2 = l2 == null ? 0 : l2.val;
            node.next = new ListNode((val1 + val2 + carry) % 10);
            carry = val1 + val2 + carry >= 10 ? 1 : 0;
            if(l1 != null)
                l1 = l1.next;
            if(l2 != null)
                l2 = l2.next;
            node = node.next;
        }
        
        if(carry == 1)
            node.next = new ListNode(1);
        return result.next;
    }
}

Reference:

http://www.cnblogs.com/springfor/p/3864493.html

2. Add Two Numbers

标签:

原文地址:http://www.cnblogs.com/yrbbest/p/4428095.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!