zoukankan      html  css  js  c++  java
  • leetcode刷题31

    今天刷的题是LeetCode第2题,两数相加,现在来做这个题还是很简单的

    首先想到的是,吧两个数都提取出来,然后相加,再生成新的链表,但是这个有个问题,就是数据有可能超过int类型的最大数。代码如下:

    public static ListNode solution(ListNode l1,ListNode l2){
            //这种做法是不正确的,因为输入的字符串有可能超过int的最大范围
            ListNode head=new ListNode(0);
            ListNode p=head;
            StringBuilder stringBuilder=new StringBuilder();
            while (l1!=null){
                stringBuilder.insert(0,l1.val);
                l1=l1.next;
            }
            StringBuilder stringBuilder2=new StringBuilder();
            while (l2!=null){
                stringBuilder2.insert(0,l2.val);
                l2=l2.next;
            }
            int sum=Integer.parseInt(stringBuilder.toString())+Integer.parseInt(stringBuilder2.toString());
            List<Integer> list=new ArrayList<>();
            while (sum!=0){
                list.add(sum%10);
                sum=sum/10;
            }
            for (int i = 0; i <list.size() ; i++) {
                ListNode listNode=new ListNode(list.get(i));
                p.next=listNode;
                p=listNode;
            }
            return head.next;
        }

    然后,因为数据是从低位到高位存储的嘛,因此,可以模拟数据相加的过程,直接相加即可。这时候需要注意的一点就是,需要一个全局的数,来保证数据是否需要进位,并且最终需要进行判断,如果所有数相加,最终有进位,那么还需要生成新的链表节点

    public static ListNode solution2(ListNode l1,ListNode l2){
            ListNode head=new ListNode(0);
            ListNode p=head;
            int pre=0;
            while (l1!=null && l2!=null){
                int num1=l1.val;
                int num2=l2.val;
                l1=l1.next;
                l2=l2.next;
                int sum=num1+num2+pre;
                ListNode newnode=new ListNode(sum%10);
                pre=sum/10;
                p.next=newnode;
                p=newnode;
            }
            ListNode others=new ListNode(0);
            if (l1!=null){
                others.next=l1;
            }else if (l2!=null){
                others.next=l2;
            }
            others=others.next;
            while (others!=null){
                int num=others.val;
                int sum=num+pre;
                ListNode newnode=new ListNode(sum%10);
                pre=sum/10;
                p.next=newnode;
                p=newnode;
                others=others.next;
            }
            if (pre!=0){
                ListNode newnode=new ListNode(pre);
                p.next=newnode;
            }
            return head.next;
        }
  • 相关阅读:
    Debian7安装msf
    Debian7配置LAMP(Apache/MySQL/PHP)环境及搭建建站
    五、docker配置镜像加速器之阿里云
    四、harbor实践之初识harbor
    三、harbor部署之SSL
    二、harbor部署之部署harbor
    超级强悍的PHP代码编辑器PHPstorm及配置
    PHP使用DomDocument抓取HTML内容
    37条常用Linux Shell命令组合
    PHP常用数组函数
  • 原文地址:https://www.cnblogs.com/cquer-xjtuer-lys/p/11517012.html
Copyright © 2011-2022 走看看