面试题 leetcode 445. Add Two Numbers II

一题目

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7

二 分析

  先尝试转换为数字,相加后在转为链表:

public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        int index1 =0;
        int index2 =0;
        ListNode cur1= l1;
        ListNode curl2 = l2;
        //转换为long
        while(cur1.next!= null) {
            index1 ++;
            cur1 = cur1.next;
        }

        while(curl2.next != null) {
            index2 ++;
            curl2 =curl2.next;
        }
        //从头重置
         cur1= l1;
         curl2 = l2;
         int max =Math.max(index1,index2);
         int max1=max;
        long num1 =0L;
        long num2 =0L;
        while(max>=0) {

            if (max == index1) {
                num1 += cur1.val *  Math.pow( 10 ,max);
                cur1 = cur1.next;
                index1--;
            }

            if (max == index2) {
                num2 += curl2.val *  Math.pow(10 , max);
                curl2 = curl2.next;
                index2--;
            }
            max--;
        }
        Long result = num1+num2;

        String str= result.toString();
        ListNode res = new ListNode(0);
        ListNode cur= res;
        for(int i=0;i<str.toCharArray().length;i++){

            cur.next =new ListNode(Integer.valueOf(str.charAt(i))-48);
            cur = cur.next;
        }

        return res.next;
    }

但是遇到这种超长的case就超出范围了。

[2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,9]
[5,6,4,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,9,9,9,9]

翻车了。那就换种思路:

这个题目跟之前的第二题两个链表相加类似,还是要复杂些。

因为哪个是链表开头就是个位数,就是可以沿着链表相加下去(从低位到高位),这个题目的链表是从高位开头的,没法直接加,还得找到低位开始加。这时候,就容易想到了使用stack,先进后出,就能从低位开始运算。

这个时间复杂度应该是O(l1+l2).

看上去还是挺慢的,得看看网上大神怎么实现的了。

TODO。

猜你喜欢

转载自blog.csdn.net/bohu83/article/details/107203662