博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode2 Add Two Numbers
阅读量:6875 次
发布时间:2019-06-26

本文共 1714 字,大约阅读时间需要 5 分钟。

描述:

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

本来想法(最笨的想法)是把两个链表都读出来组成数字,反转相加,再将二者的和反转存到一个链表,经谷歌提点,本来两个链表就是从个位开始的,一位一位相加,进位在下个高位继续加。

public class Solution {    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {        ListNode head = new ListNode(0);    // empty header;        ListNode resCur = head;        ListNode cursor1 = l1;        ListNode cursor2 = l2;        int remad=0;        int m=0;        while(cursor1!=null || cursor2!=null){            int sum=0;            int val1=0;            int val2=0;            if(cursor1!=null){                val1=cursor1.val;            }            if(cursor2!=null){                val2=cursor2.val;            }            sum=val1+val2+remad;            remad=sum/10;            m=sum%10;            resCur.next=new ListNode(m);            resCur=resCur.next;            if(cursor1!=null)                cursor1=cursor1.next;            if(cursor2!=null)                cursor2=cursor2.next;        }        if(remad!=0)            resCur.next=new ListNode(remad);        return head.next;    }    public static  void main(String[] args){        ListNode l1=new ListNode(5);        l1.next=new ListNode(4);        ListNode l2=new ListNode(5);        l2.next=new ListNode(5);        ListNode resNum=new ListNode(0);        resNum=addTwoNumbers(l1,l2);        while (resNum!=null){            System.out.print(resNum.val+"->");            resNum=resNum.next;        }    }}

转载于:https://www.cnblogs.com/duanqiong/p/4403570.html

你可能感兴趣的文章
【Mongodb】3.X 配置身份验证
查看>>
云计算就像马拉松 京东CTO为啥这么说
查看>>
「每天一道面试题」Java虚拟机为新生对象分配内存有哪两种方式?
查看>>
海信电器于芝涛:坚守画质 才是消费者首选
查看>>
直播竞答必读:一定要提前知道的技术坑和新玩法
查看>>
React 中集成 Markdown编辑器
查看>>
Spring Boot 最佳实践(五)Spring Data JPA 操作 MySQL 8
查看>>
由三道题引伸出来的思考
查看>>
React 开发实战(一)- Repeat 组件
查看>>
小程序云开发全套实战教程(最全)
查看>>
单页引用中使用百度地图
查看>>
对 PHP 中依赖注入和控制反转的理解
查看>>
springMVC原理
查看>>
[Python3网络爬虫开发实战] 2-爬虫基础 3-爬虫的基本原理
查看>>
Java IO输入输出及乱码问题
查看>>
Linux服务器配置——简介
查看>>
react项目中使用mocha结合chai断言库进行单元测试
查看>>
nfs
查看>>
Angular vs React 最全面深入对比
查看>>
containerd项目正式从CNCF毕业
查看>>