`
junfeng_feng
  • 浏览: 19899 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

LeetCode Interview Qustions: Add Two Number

 
阅读更多

直接使用加法

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        ListNode* result = new ListNode(0);
        ListNode* p = result;
        int carray_bit = 0;
        while(l1 && l2) {
            p->next = new ListNode(0);
            p = p->next;
            
            p->val = l1->val + l2->val + carray_bit;
            if (p->val >= 10) {
                p->val = p->val%10;
                carray_bit = 1;
            } else {
                carray_bit = 0;
            }
            l1 = l1->next;
            l2 = l2->next;
        }
        
        while(l1) {
            p->next = new ListNode(0);
            p = p->next;
            
            p->val = l1->val + carray_bit;
            if (p->val >= 10) {
                p->val = p->val%10;
                carray_bit = 1;
            } else {
                carray_bit = 0;
            }
            l1 = l1->next;
        }
        
        while(l2) {
            p->next = new ListNode(0);
            p = p->next;
            
            p->val = l2->val + carray_bit;
            if (p->val >= 10) {
                p->val = p->val%10;
                carray_bit = 1;
            } else {
                carray_bit = 0;
            }
            l2 = l2->next;
        }
        
        if (carray_bit) {
            p->next = new ListNode(1);
            p = p->next;            
        }
        return result->next;        
    }
};


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics