首页 > 其他 > 详细

Add Two Numbers

时间:2014-03-29 08:15:44      阅读:385      评论:0      收藏:0      [点我收藏+]

 

代码:

bubuko.com,布布扣
/**
 * 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) {
              ListNode result = null;

        ListNode temp = null, node = null;
        int digit = 0, bit = 0;
        while (l1 != null && l2 != null) {
            digit = l1.val + l2.val + bit;
            bit = digit / 10;
            digit = digit % 10;
            node = new ListNode(digit);
            if (result == null) {
                result = node;
                temp = result;
            } else {
                temp.next = node;
                temp = temp.next;
            }
            l1 = l1.next;
            l2 = l2.next;
        }

        while (l1 != null) {
            digit = l1.val + bit;
            bit = digit / 10;
            digit = digit % 10;
            node = new ListNode(digit);
            if (result == null) {
                result = node;
                temp = result;
            } else {
                temp.next = node;
                temp = temp.next;
            }
            l1 = l1.next;
        }

        while (l2 != null) {
            digit = l2.val + bit;
            bit = digit / 10;
            digit = digit % 10;
            node = new ListNode(digit);
            if (result == null) {
                result = node;
                temp = result;
            } else {
                temp.next = node;
                temp = temp.next;
            }
            l2 = l2.next;
        }

        if (bit != 0) {
            node = new ListNode(bit);
            if (result == null) {
                result = node;
                temp = result;
            } else {
                temp.next = node;
                temp = temp.next;
            }
        }
        return result;
    }
}
bubuko.com,布布扣

Add Two Numbers,布布扣,bubuko.com

Add Two Numbers

原文:http://www.cnblogs.com/xiaoxian1369/p/3631974.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!