LeetCode No.0002 两数相加

问题描述:

  给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

  如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

  您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

解题思路:

  (1)我想要将所有的链表中的数转换到一个整数中,将得到的两个整数相加,得到其和,再将其和按位分到新的链表中。

      遇到问题:int型变量最多只能容纳8位,long型只能容纳16位,连String型可容纳65534位都不能通过测试用例。有毛病……

以下代码无法通过检测!!!

/**
 * 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) {
        List<Integer>m1 = new ArrayList<Integer>();
        List<Integer>m2 = new ArrayList<Integer>();
        String s1 = new String();
        String s2 = new String();
        ListNode sol = new ListNode(0);
        ListNode sol2 = new ListNode(0);
        sol.next = sol2;
        while(l1.next != null){
            m1.add(l1.val);
            l1 = l1.next;
        }
        for(int i = 0; i < m1.size(); ++i){
            String s = "" + m1.get(m1.size()-1-i);
            s1 += s;
        }
        while(l2.next != null){
            m2.add(l2.val);
            l2 = l2.next;
        }
        for(int i = 0; i < m2.size(); ++i){
            String s = "" + m2.get(m1.size()-1-i);
        }
        int i = Integer.valueOf(s1) + Integer.valueOf(s2);
        while(i > 0){
            sol2.val = i % 10;
            i = i / 10;
            sol2.next = new ListNode(0);
            sol2 = sol2.next;
        }
        return sol2;
    }
}

  (2)转换思路,将所有链表中的值按位相加,正巧,链表是倒序表示的(原来题目已经明示解题思路……)问题迎刃而解,反而是出奇的简单。代码如下:

/**
 * 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 head = new ListNode(0);
        ListNode curr = head;
        int carry = 0;
        while(l1 != null || l2 != null){
            int x = (l1 != null)? l1.val : 0;
            int y = (l2 != null)? l2.val : 0;
            int sum = x + y + carry;
            carry = sum /10;
            curr.next = new ListNode(sum % 10);
            curr = curr.next;
            if(l1 != null) l1 = l1.next;
            if(l2 != null) l2 = l2.next;
        }
        if(carry == 1){
            curr.next = new ListNode(1);
        }
        return head.next;
    }
}

  顺利通过。时间复杂度O(max(m,n)),m和n分别代表两个链表的长度。取最大值代表循环的次数。

  

猜你喜欢

转载自www.cnblogs.com/wenzhao/p/12241178.html
今日推荐