【问题标题】:Adding two linked lists from the end [ DUPLICATE]从末尾添加两个链表[重复]
【发布时间】:2023-04-07 12:13:02
【问题描述】:

我有两个链表,每个节点都包含一个数字。数字顺序相反,因此 1 的数字位于列表的开头。我必须编写一个函数,将两个数字相加并返回总和。 我在互联网上看到了很多解决方案,并提出了自己的解决方案。我想知道使用 StringBuilder 将数字转换为字符串是否是一种有效的方法。

public int addlists(Node head,Node head2) {
    int sum = 0;
    Node n = head;
    Node n2 = head2;
    StringBuilder s = new StringBuilder();
    StringBuilder s2 = new StringBuilder();
    while(n!=null) {
        s.append(n.data);
        n = n.next;
    }

    while(n2!=null) {
        s2.append(n2.data);
         n2 = n2.next;
    }

    s.reverse(); s2.reverse();

    sum = Integer.parseInt(s.toString()) + Integer.parseInt(s2.toString());
    System.out.println(sum);
    return sum;
}

【问题讨论】:

  • 您将问题标记为重复?
  • 您是否在问题标题中手动添加了 [DUPLICATE]?

标签: java data-structures linked-list singly-linked-list


【解决方案1】:

您不需要使用StringBuilder,您可以使用简单的数学来做到这一点,只需跟踪生成的carry,然后使用Math.pow 将十位乘以10 和百位乘以100

public int addTwoLists(Node first, Node second) {
    int carry=0,sum=0,k=0;

    while (first != null || second != null){

        sum = sum + ((carry+(first!=null?first.data:0)+(second!=null?second.data:0))%10) * ((int)(Math.pow(10,k)));

        carry=(carry+(first!=null?first.data:0)+(second!=null?second.data:0)>=10)?1:0;

        k++;
        if (first != null) { first = first.next; }
        if (second != null) { second = second.next; }
    }
    return sum;
}

【讨论】:

    猜你喜欢
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多