0002-Add Two Numbers

题目

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

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

示例

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

解题

解法一

和小时候学的竖式加法一样,从最小的一位,即从列表的第一个元素开始加起。遇到进位先保存,然后加入下一位即可。注意,两个列表不一定是相同长度的。

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {
   public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
       ListNode tmp = null;
       ListNode result = null;

       int carry = 0;
       while (l1 != null || l2 != null || carry != 0) {
           int sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry;
           carry = sum / 10;

           ListNode node = new ListNode(sum % 10);
           if (tmp == null) {
               tmp = node;
               result = tmp;
           } else {
               tmp.next = node;
               tmp = tmp.next;
           }

           l1 = l1 == null ? null : l1.next;
           l2 = l2 == null ? null : l2.next;
       }

       return result;
   }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Cyber-dojo.org是编程操练者的乐园。下面是这个网站上的43个编程操练题目,供编程操练爱好者参考。 10...
    程序员吾真本阅读 5,875评论 1 2
  • 题目概要 完成两个链表的“加法”并返回存储“和”的链表。 题目链接 Add Two Numbers 解题思路 迭代...
    大圣软件阅读 1,332评论 0 0
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 13,151评论 0 13
  • 为了使我自己更快的成长和提升,也为了成为更好的自己,连续21天每天写出自己的十大优点,今天是打卡第12天: 1.我...
    梅子Mey阅读 3,660评论 0 1
  • 我见过九曲十八弯的河流在山间流淌,满眼之处皆是青山绿水的纯净, 见过从前有座山,山上有房子,房子就被山上的树木簇拥...
    陈七不要十三阅读 1,300评论 0 0