leetcode刷题日记——两数相加

题目描述

思路

  • 通过两个循环将 l1, l2存储的数字读出,然后求和,再将结果存储链表中

  • 由此发了一个问题,结果溢出,如果使用更大的 long 类型,后续不出所料,仍然超出

  • 所以只能转换思路

    /**

    • Definition for singly-linked list.
    • struct ListNode {
    • 复制代码
      int val;
    • 复制代码
      struct ListNode *next;
    • };
      /
      struct ListNode
      addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
      int num1=0,num2=0,res=0,index=0;
      while(l1){
      num1=num1+l1->valpow(10,index++);
      l1=l1->next;
      }
      index=0;
      while(l2){
      num2=num2+l2->val
      pow(10,index++);
      l2=l2->next;
      }
      res=num1+num2;
      struct ListNode* head=(struct ListNode*)malloc(sizeof(struct ListNode));
      struct ListNode* rear=head;
      if(res==0){
      rear->next=(struct ListNode*)malloc(sizeof(struct ListNode));
      rear=rear->next;
      rear->val=0;
      }else{
      while(res!=0){
      rear->next=(struct ListNode*)malloc(sizeof(struct ListNode));
      rear=rear->next;
      rear->val=res%10;
      res/=10;
      }
      }
      rear->next=NULL;
      return head->next;
      }
  • 既然不能一次性存储所有结果,那么就只能模拟加法器,一位一位的计算

  • 运行如下

    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    int carry=0;
    struct ListNode* head=(struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* rear=head;
    while(l1 || l2 || carry!=0){
    int num1=0,num2=0;
    if(l1){
    num1=l1->val;
    l1=l1->next;
    }
    if(l2){
    num2=l2->val;
    l2=l2->next;
    }
    carry+=num1+num2;
    rear->next=(struct ListNode*)malloc(sizeof(struct ListNode));
    rear=rear->next;
    rear->val=carry%10;
    carry/=10;
    }
    rear->next=NULL;
    return head->next;
    }

官方题解

  • 方法一:模拟,具体思路同上
相关推荐
Cx330_FCQ32 分钟前
Tmux使用
服务器·git·算法
拳里剑气2 小时前
C++算法:多源BFS
c++·算法·宽度优先·多源bfs
ysa0510302 小时前
【板子】短序列dp(换成维护更小常数维度的dp)
c++·笔记·算法·板子
shwill1232 小时前
PID 算法(三)--- 增量 PID ↔ 单神经元 PID 等价映射
linux·算法
wabs6664 小时前
关于图论【卡码网110.字符串迁移的思考】
数据结构·算法·图论
hanlin034 小时前
刷题笔记:力扣第242、349题(哈希表)
笔记·算法·leetcode
浮沉9875 小时前
二分查找算法例题(二)
算法
only-qi5 小时前
大模型Agent面试攻略:落地工程痛点、评估体系与Agentic RAG核心精讲
人工智能·算法·面试·职场和发展·langchain·rag
数字宝藏6 小时前
15本电子书分享
职场和发展·职场发展·教育电商
Gauss松鼠会7 小时前
【GaussDB】GaussDB锁阻塞源头查询
java·开发语言·前端·数据库·算法·gaussdb·经验总结