2.Add Two Numbers

给定2个链表,每个链表所代表的数字是反着排列的,比如整数:123,在链表中是 3->2->1,让你求这两个数之和,并也将其和反着排列。
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.


思路:
一开始将2个数字表示出来,求得和,再装进新链表返回,但是发现数字太大,超出了int, long long 的范围。所以只有换一种方式,将链表表示的数字存为字符串 s1, s2,对字符串中的值遍历,与进位flag相加,若超过10,则进位flag = 1. 由于2个字符串可能不相等,所以先将短的那个填充 0 ,使得两个字符串等长。若遍历完字符串flag = 1,则链表后接一个1.

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    string s1 = "", s2 = "";
    ListNode* head = new ListNode(-1), * p = head;
    while (l1) {
        s1 += to_string(l1->val);
        l1 = l1->next;
    }
    while (l2) {
        s2 += to_string(l2->val);
        l2 = l2->next;
    }
    int sub = s1.size() > s2.size() ? s1.size() - s2.size() : s2.size() - s1.size();
    if (s1.size() > s2.size()){
        for (int i = 0; i < sub; i++) s2 += '0';
    }
    if (s2.size() > s1.size()) {
        for (int i = 0; i < sub; i++) s1 += '0';
    }
    int flag = 0, sum = 0;
    for (int i = 0; i < s1.size(); i++) {
        sum = (s1[i] - '0') + (s2[i] - '0') + flag;
        ListNode* tmp;
        if (sum >= 10) {
            tmp = new ListNode(sum - 10);
            flag = 1;
        }
        else {
            tmp = new ListNode(sum);
            flag = 0;
        }
        sum = 0;
        p->next = tmp;
        p = p->next;
    }
    if (flag == 1) p->next = new ListNode(1);
    return head->next;
}

 

总结:在对字符串填充的时候,使用 for(int i=0; i< s1.size( ) - s2.size( ) ; i++) { s2 += '0'},由于字符串 s2 在不断填充,所以 s2的长度是不断增加的,所以, s1.size( ) - s2.size( )是越来越小的,不是固定的,所以不能这样写

 

二、参考别人的写法。

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    ListNode* head = new ListNode(-1), * tmp = head;
    int sum = 0, flag = 0;
    while (l1 || l2) {
        int val1 = l1 ? l1->val : 0;
        int val2 = l2 ? l2->val : 0;
        sum = val1 + val2 + flag;
        flag = sum / 10;
        tmp->next = new ListNode(sum % 10);
        tmp = tmp->next;
        l1 = l1 ? l1->next : NULL;
        l2 = l2 ? l2->next : NULL;
    }
    if (flag == 1) tmp->next = new ListNode(1);
    return head->next;
}

 

Java 版:

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode res = new ListNode(-1), resHead = res;
        int flag = 0, val = 0, n1 = 0, n2 = 0;
        while(l1 != null || l2 != null){
            n1 = l1 == null ? 0 : l1.val;
            n2 = l2 == null ? 0 : l2.val;
            val = (n1 + n2 + flag) % 10;
            flag = (n1 + n2 + flag) / 10;
            res.next = new ListNode(val);
            l1 = l1 == null ? l1 : l1.next; 
            l2 = l2 == null ? l2 : l2.next; 
            res = res.next;
        }
        if(flag > 0){
            res.next = new ListNode(flag);
        }
        return resHead.next;
    }
}

 

posted @ 2020-05-15 14:42  星海寻梦233  阅读(139)  评论(0编辑  收藏  举报