zoukankan      html  css  js  c++  java
  • Leetcode: 2. Add Two Numbers

    一直想用一个进位变量来存贮进位值,但老是考虑不周全,下面是我自己写的bug代码,考虑不周,因为l1或者l2都有可能为null

    class Solution {
         public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
                ListNode listEnd = new ListNode(0);
                ListNode list = listEnd;
                
                int carry = 0;
                while (l1 != null || l2 != null) {
                    int sum = 0;
                    if(l1!=null) {
                        sum =carry+l1.val;
                        l1 = l1.next;
                        
                    }
                    if(l2!=null) {
                        sum =l2.val+sum;
                        l2 = l2.next;
                    }
                    
                    list.next = new ListNode(sum % 10);
                    carry = sum/10;
                    list = list.next;
                }
                if (carry== 1)
                    list.next = new ListNode(1);
                return listEnd.next;
            }
    }

    acccpt:https://discuss.leetcode.com/topic/799/is-this-algorithm-optimal-or-what

    import java.util.Map;
    
    public class Test2 {
         public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
                ListNode listEnd = new ListNode(0);   //作为最后返回的链表,返回的是next
                ListNode list = listEnd;  //一直在遍历的链表,因为list指针一直是往后移动,所以只用一个指针是完成不了任务的,必须有一个作为缓存
                int sum = 0;
             
                while (l1 != null || l2 != null) {
                    sum =sum/10;     //求进位,这里就只能用这种方式。我一直在想用一个变量来存储,但往往会考虑不周
                    if(l1!=null) {
                        sum =sum+l1.val;
                        l1 = l1.next;
                        
                    }
                    if(l2!=null) {
                        sum =sum+l2.val;
                        l2 = l2.next;
                    }
                    
                    list.next = new ListNode(sum % 10);    //动态产生链表节点
                 
                    list = list.next;
                }
                if (sum / 10 == 1)      //最后的和大于10的话,则进位
                    list.next = new ListNode(1);
                return listEnd.next;
            }
    }
  • 相关阅读:
    flask的类视图
    flask的消息提示flash和abort
    css—left和margin-left的区别
    Git(2)—特性
    JS 基础
    css
    搭建vue环境
    Git(1)—基础
    C中 输出格式
    软件测试_对于堆栈的单元测试
  • 原文地址:https://www.cnblogs.com/Michael2397/p/8025059.html
Copyright © 2011-2022 走看看