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

lintcode-easy-Add two numbers

时间:2016-02-21 11:23:13      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1‘s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.

Example

Given 7->1->6 + 5->9->2. That is, 617 + 295.

Return 2->1->9. That is 912.

Given 3->1->5 and 5->9->2, return 8->0->8.

 

这题也没太多可说的,和把两个二进制数加起来那题差不多

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;      
 *     }
 * }
 */
public class Solution {
    /**
     * @param l1: the first list
     * @param l2: the second list
     * @return: the sum list of l1 and l2 
     */
    public ListNode addLists(ListNode l1, ListNode l2) {
        // write your code here
        
        if(l1 == null)
            return l2;
        if(l2 == null)
            return l1;
        
        ListNode fakehead = new ListNode(0);
        ListNode p = fakehead;
        
        ListNode p1 = l1;
        ListNode p2 = l2;
        
        int carry = 0;
        
        while(p1 != null || p2 != null){
            int num1 = 0;
            int num2 = 0;
            
            if(p1 !=null){
                num1 = p1.val;
                p1 = p1.next;
            }
            if(p2 != null){
                num2 = p2.val;
                p2 = p2.next;
            }
            
            p.next = new ListNode((num1 + num2 + carry) % 10);
            p = p.next;
            
            carry = (num1 + num2 + carry) / 10;
        }
        
        if(carry == 1){
            p.next = new ListNode(1);
            p = p.next;
        }
        
        return fakehead.next;
    }
}

 

lintcode-easy-Add two numbers

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5204505.html

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