• Add Two Numbers


    You are given two linked lists representing two non-negative numbers. 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

    struct ListNode {
        int val;
         ListNode *next;
        ListNode(int x) : val(x), next(NULL) {}
    };
    
    /*
        最直白的想法就是将两个字符串翻转, 然后相加,得到的结果再发转
        现在的解法,直接从左到右相加,然后向右进位
    */
    
    class Solution {
    public:
        ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
            
            ListNode* ptr = new ListNode(0);  
            ListNode* head = ptr; 
            int tmp_carry = 0;
            int sum;
    
            while( l1 || l2 )
            {
                 sum = 0;
                 if( l1 )
                 {
                    sum += l1->val;
                    l1 = l1->next;
                 }
    
                 if( l2 )
                 {
                    sum += l2->val;
                    l2 = l2->next;
                 }
            
                 ptr->next = new ListNode( (sum + tmp_carry)%10 );  
                 ptr = ptr->next;
                 tmp_carry = (sum + tmp_carry)/10;
            }
    
            if( tmp_carry )
            {
                 ptr->next = new ListNode( tmp_carry );  
            }
            return head->next;
        }
    };
    当你的才华还撑不起你的野心时,那你就应该静下心来学习。
  • 相关阅读:
    循环队列
    快速排序
    单链表
    数学之美总结
    我要的生活...
    北京,我来了
    冷暖自知 by 张楚
    瞎掰,关于网站的推广和如何摧毁贴吧<上>
    Adobe 拟发布WEB PS
    Web阅读摘录[持续更新]
  • 原文地址:https://www.cnblogs.com/aceg/p/4423425.html
Copyright © 2020-2023  润新知