leetcode第二题AddTwoNumber

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.
给定两个非空的链表,表示两个非负整数。 数字以相反的顺序存储,每个节点包含一个数字。 添加两个数字并将其作为链表返回。
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

emmm,就是链表对应的相加,有进位的进位到下一个相加的节点,null的当做0来计算,只要把进位符号加到下一个节点就行了。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
         ListNode shit = new ListNode(0);
        ListNode temp  =shit;
        ListNode a = l1;
        ListNode b = l2;
        int carry = 0;//表示进位符号
        while (a!=null||b!=null)
        {
            //如果有个链表短,则空的就当做0,
            int first = (a==null)?0:a.val;
            int second = (b==null)?0:b.val;
            int sum = first+second+carry;
            carry = sum/10;
            temp.next = new ListNode(sum%10);
            temp = temp.next;
            if(a!=null)a = a.next;
            if(b!=null)b = b.next;
        }
        if(carry>0){//这里如果到了最后一位加还有一个进位的时候要多加一个节点
            temp.next = new ListNode(carry);
        }
        return shit.next;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章