zoukankan      html  css  js  c++  java
  • 【中级算法】6.两数相加

    题目:

    给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
    
    你可以假设除了数字 0 之外,这两个数字都不会以零开头。
    
    示例:
    
    输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
    输出:7 -> 0 -> 8
    原因:342 + 465 = 807
    

     解法:

    /**
     * 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) {
            if(l1 == NULL){
                return l2;
            }
            if(l2 == NULL){
                return l1;
            }
            
            ListNode * head = NULL;
            ListNode * pre = NULL;
            int carry = 0;
            while(l1&&l2){
                ListNode * newNode = new ListNode((l1->val + l2->val + carry)%10);
                carry = (l1->val + l2->val + carry)/10;
                if(head == NULL){
                    head = newNode;
                    pre = head;
                }else{
                    pre->next = newNode;
                    pre = newNode;
                }
                l1 = l1->next;
                l2 = l2->next;
            }
            
            while(l1){
                ListNode * newNode = new ListNode((l1->val + carry)%10);
                carry = (l1->val + carry)/10;
                pre->next = newNode;
                pre = newNode;
                l1 = l1->next;
            }
            
            while(l2){
                ListNode * newNode = new ListNode((l2->val + carry)%10);
                carry = (l2->val + carry)/10;
                pre->next = newNode;
                pre = newNode;
                l2 = l2->next;
            }
            
            if(carry > 0){
                ListNode * newNode = new ListNode(carry);
                pre->next = newNode;
                pre = newNode;
            }
                    
            return head;
        }
    };
    

      

  • 相关阅读:
    Sicily shortest path in unweighted graph
    Sicily connect components in undirected graph
    Sicily 1931. 卡片游戏
    Sicily 1021. Couples
    c++ 高效文本读写
    Sicily 1129. ISBN
    Sicily 1133. SPAM
    Sicily 1282. Computer Game
    小工具?不,这是小工具的集合!
    .Net Core建站(4):FTP发布项目及连接服务器数据库
  • 原文地址:https://www.cnblogs.com/mikemeng/p/9206959.html
Copyright © 2011-2022 走看看