• 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

    思路:注意检查validation!因为都是digit,在%和/可以改成bit opertiaon 来提高效率 【待优化】

    /**
     * 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) {
            //check invalidation
            if(l1==NULL) return l2;
            if(l2==NULL) return l1;
            ListNode *rel,*head;
            rel=head=new ListNode(0);
            ListNode *p1=l1;
            ListNode *p2=l2;
            int carry=0;
            int sum=0;
            while(p1&&p2){
                sum = p1->val+p2->val+carry;
                ListNode *node = new ListNode(0);
                node->val = sum%10;
                carry = sum/10;
                rel->next=node;
                
                rel=rel->next;
                p1=p1->next;
                p2=p2->next;
            }
            
            //when p1.length != p2.length
            ListNode *p;
            if(p1==NULL) p=p2;
            else p=p1;
            while(p)
            {
                sum = p->val+carry;
                ListNode *node = new ListNode(0);
                node->val = sum%10;
                carry = sum/10;             
                rel->next=node;
                rel=rel->next;
                p=p->next;
            }
            
            //when highest bit needs carrying operation
            if(carry!=0){
                ListNode *node = new ListNode(0);
                node->val = carry;
                rel->next=node;
            }
            
            return head->next;
            
        }
    };
  • 相关阅读:
    ThinPHP v5.x安装初始化配置(项目实战)
    Bresenham快速画直线算法
    arm笔记之MOV
    Blackfin DSP的C语言优化之Circular Buffer
    Visual DSP定点数(fract)使用指南
    全局二值化
    Blackfin DSP学习心得与参考资料
    Linux网络配置
    一般方程与参数方程求直线交点
    一个改进的快速排序实现
  • 原文地址:https://www.cnblogs.com/renrenbinbin/p/4384983.html
Copyright © 2020-2023  润新知