zoukankan      html  css  js  c++  java
  • LeetCode T2

     

     使用依次相加,记录进位的方式进行运算,下面是我的解答,leetcode上运行耗时20ms,内存占用7.3MB

    struct ListNode{
        int val;
        struct ListNode *next;
    };
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
        struct ListNode *p1,*p2;
        p1=l1;p2=l2;
        struct ListNode *head=(struct ListNode *)malloc(sizeof(struct ListNode));
        head->next=NULL;
        struct ListNode *q=head;
        int flag_pre=0,flag_this=0;//用来记录进位
        while(p1 || p2){
            int tmp=0;
            if(p1==NULL && p2) tmp=p2->val+flag_pre;
            else if(p2==NULL && p1) tmp=p1->val+flag_pre;
            else tmp=p1->val+p2->val+flag_pre;
            flag_pre=0;
            if(tmp>=10){
                flag_this=1;
                flag_pre=1;
            };
            struct ListNode *tail=(struct ListNode *)malloc(sizeof(struct ListNode));
            tail->val=tmp-flag_this*10;
            flag_this=0;
            tail->next=NULL;
            q->next=tail;
            q=q->next;
            if(p1) p1=p1->next;
            if(p2) p2=p2->next;
        }
        if(!(p1&&p2) && flag_pre==1){
            struct ListNode *tail=(struct ListNode *)malloc(sizeof(struct ListNode));
            tail->val=1;
            tail->next=NULL;
            q->next=tail;
            q=q->next;
        }
        return head->next;
    }
  • 相关阅读:
    区间筛——模板
    I NEED A OFFER!
    dp入门(A)
    java如何创建类
    二维数组
    一维数组
    循环练习记录
    根据浏览器屏幕分辨率不同使用不同的css样式——响应式
    jquery 淡入淡出动画效果例子
    toggle()在新闻热点上的运用
  • 原文地址:https://www.cnblogs.com/runsdeep/p/12786669.html
Copyright © 2011-2022 走看看