445:Add Two Numbers II

Question:

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7


題目意思:
兩個數(shù)字鏈表形式給出,求和


代碼如下:
答題思路,將兩個鏈表存放到兩個數(shù)組中去,缺失的高位用0填補,每次計算類似加法器,設(shè)置一個進位計數(shù)器carry,每次取相應(yīng)位于進位計數(shù)器相加求得相應(yīng)數(shù)值與下一個進位,最后需要對進位進行判斷,如果大于0則再加一位。
<pre>
/**

  • Definition for singly-linked list.

  • struct ListNode {

  • int val;
    
  • struct ListNode *next;
    
  • };
    /
    struct ListNode
    addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    int length1 = 0;
    struct ListNode* p1 = l1;
    while(p1 != NULL) {
    length1++;
    p1 = p1->next;
    }

    int length2 = 0;
    struct ListNode* p2 = l2;
    while(p2 != NULL) {
    length2++;
    p2 = p2->next;
    }

    int length = length1 > length2 ? length1 : length2;
    int arr1[length];
    int arr2[length];
    for(int i = 0; i < length; i++) {
    arr1[i] = 0;
    arr2[i] = 0;
    }

    p1 = l1;
    for(int posi1 = length - length1; posi1 <= length -1; posi1++) {
    arr1[posi1] = p1->val;
    p1 = p1->next;
    }

    p2 = l2;
    for(int posi2 = length - length2; posi2 <= length -1; posi2++) {
    arr2[posi2] = p2->val;
    p2 = p2->next;
    }

    int carry = 0;
    int plus = 0;
    struct ListNode* ans = NULL;
    for(int i = length;i >= 1; i--) {
    plus = (arr1[i-1] + arr2[i-1] + carry)%10;
    carry = (arr1[i-1] + arr2[i-1] + carry)/10;
    struct ListNode* temp = (struct ListNode*)malloc(sizeof(struct ListNode));
    temp->val = plus;
    temp->next = ans;
    ans = temp;
    }

    struct ListNode* head = NULL;
    if(carry != 0) {
    head = (struct ListNode*)malloc(sizeof(struct ListNode));
    head->val = carry;
    head->next = ans;
    }else {
    head = ans;
    }
    return head;
    }
    </pre>

吐槽下:lettcode為什么不支持int a[3] = {0}的初始化方式,= =,戰(zhàn)戰(zhàn)兢兢想著默認會是0,結(jié)果不是= =


看了排行第一的解答= = 先把鏈表翻轉(zhuǎn)= =然后該干啥干啥
我簡直是個弱智

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容