leetcode 2.两数相加

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,而且它们的每一个节点只能存储 一位 数字。网络

若是,咱们将这两个数相加起来,则会返回一个新的链表来表示它们的和。code

您能够假设除了数字 0 以外,这两个数都不会以 0 开头。leetcode

示例:it

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
缘由:342 + 465 = 807io

来源:力扣(LeetCode)
连接:https://leetcode-cn.com/problems/add-two-numbers
著做权归领扣网络全部。商业转载请联系官方受权,非商业转载请注明出处。class

 

 

 

 

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }//新建有参构造方法
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode pre = new ListNode(0);
        ListNode cur = pre;//将pre的地址赋给cur
        int carry = 0;
        while(l1 != null || l2 != null) {//while循环条件为只要有一个链表不空就继续进行
            int x = l1 == null ? 0 : l1.val;//空的
            int y = l2 == null ? 0 : l2.val;
            int sum = x + y + carry;
            
            carry = sum / 10;
            sum = sum % 10;
            cur.next = new ListNode(sum);List

            cur = cur.next;
            if(l1 != null)
                l1 = l1.next;
            if(l2 != null)
                l2 = l2.next;
        }
        if(carry == 1) {
            cur.next = new ListNode(carry);
        }
        return pre.next;
    }
}循环

做者:guanpengchn
连接:https://leetcode-cn.com/problems/add-two-numbers/solution/hua-jie-suan-fa-2-liang-shu-xiang-jia-by-guanpengc/
来源:力扣(LeetCode)
著做权归做者全部。商业转载请联系做者得到受权,非商业转载请注明出处。gc

相关文章
相关标签/搜索