使用字符串添加两个给定的数字(链接列表中的数字)

时间:2016-08-19 13:01:31

标签: java string linked-list

我正在尝试添加两个非负数,其中的数字以相反的顺序存储在两个单独的链接列表中。答案也应该是一个链表,数字反转,没有尾随零。

据我所知,有一种方法可以通过添加数字和每次维持一个进位来解决这个问题,但我试图通过对数字使用加法运算来解决它。

这是我的代码:

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     public int val;
     *     public ListNode next;
     *     ListNode(int x) { val = x; next = null; }
     * }
     */
    public class Solution {
        public ListNode addTwoNumbers(ListNode a, ListNode b) {
            if(a==null || b==null){
                return null;


}
        String num1 = "";
        String num2 = "";
        ListNode temp1 = a;
        ListNode temp2 = b;
        while(temp1!=null){
            num1 = num1+Integer.toString(temp1.val);
            temp1 = temp1.next;
        }
        new StringBuilder(num1).reverse().toString();
        double value1 = Double.parseDouble(num1);
        while(temp2!=null){
            num2 = num2+Integer.toString(temp2.val);
            temp2 = temp2.next;
        }
        new StringBuilder(num2).reverse().toString();
        double value2 = Double.parseDouble(num2);
        double result = value1+value2;
        String res = String.format("%.0f",result);
        ListNode first_node =  new ListNode(Character.getNumericValue(res.charAt(0)));
        ListNode ans  = first_node;
        for(int j=1;j<res.length();j++){
            ListNode node = new ListNode(Character.getNumericValue(res.charAt(j)));
            add(node,ans);
        }
        return ans;
    }
    public void add(ListNode node, ListNode ans){
        ListNode temp;
        temp = ans;
        ans  = node;
        ans.next = temp;
    }
}

我的代码一直给出错误的答案。任何人都可以指出错误吗?

5 个答案:

答案 0 :(得分:0)

您的方法不正确且间接。 你正在尝试使用浮点运算来做大数字算术。 结果 - 计算错误。

我们有:

List<Integer> firstNumber;
List<Integer> secondNumber;

假设 firstNumber > secondNumber

试试这个算法:

List<Integer> result = new ArrayList<>();
int i = 0;
int appendix = 0;
for (; i < secondNumber.size(); i++) {
    int sum = firstNumber.get(i) + secondNumber.get(i) + appendix;
    result.append(sum % 10);
    appendix = sum / 10;
}

for (; i < firstNumber.size(); i++) {
    int sum = firstNumber.get(i) + appendix;
    result.append(sum % 10);
    appendix = sum / 10;
}

if (appendix != 0) 
    result.append(appendix);

return result;

答案 1 :(得分:0)

您的添加功能看起来不正确。您将以与预期相反的顺序获得编号。

此外,您的解决方案缺少问题的要点。如果你有一个有很多数字的数字你的方法将会失败(即使是双倍的限制,我认为它是2 ^ 1024)。链表表示允许数字更大。

正确的解决方案是在创建解决方案列表的同时,使用进位数同时迭代两个列表。如果这是作业或编码竞赛中的问题,那么您的解决方案将被判定为错误。

答案 2 :(得分:0)

您的add方法错误,它没有正确构建列表。以下是您的方法的最后部分应该如何看,没有add方法:

for(int j=1;j<res.length();j++){
   ans.next = new ListNode(Character.getNumericValue(res.charAt(j)));;
   ans = ans.next;
}
return first_node;

答案 3 :(得分:0)

在您的方法中,变量ans不会更新。你可以试试这个:

ans = add(node,ans);

并在您的add方法中,更改方法以返回ListNode ans

答案 4 :(得分:0)

您的方法并不简单,也不会给您预期的结果。

这是一个简单的方法,不需要太多解释,因为加法是整数的简单整数。

请注意,当两个整数之和大于9时,我继续前进,否则继续使用列表中下一个整数的总和。

class Node {
    private Object data;
    private Node next;
    public Object getData() { return data; }
    public void setData(Object data) {  this.data = data; }
    public Node getNext() { return next; }
    public void setNext(Node next) { this.next = next; }
    public Node(final Object data, final Node next) {
        this.data = data;
        this.next = next;
    }
    @Override
    public String toString() { return "Node:[Data=" + data + "]"; }
}


class SinglyLinkedList {
    Node start;
    public SinglyLinkedList() { start = null; }

    public void addFront(final Object data) {
        // create a reference to the start node with new data
        Node node = new Node(data, start);

        // assign our start to a new node
        start = node;
    }

    public void addRear(final Object data) {
        Node node = new Node(data, null);
        Node current = start;

        if (current != null) {
            while (current.getNext() != null) {
                current = current.getNext();
            }
            current.setNext(node);
        } else {
            addFront(data);
        }
    }

    public void deleteNode(final Object data) {
        Node previous = start;

        if (previous == null) {
            return;
        }

        Node current = previous.getNext();

        if (previous != null && previous.getData().equals(data)) {
            start = previous.getNext();
            previous = current;
            current = previous.getNext();
            return;
        }

        while (current != null) {
            if (current.getData().equals(data)) {
                previous.setNext(current.getNext());
                current = previous.getNext();
            } else {
                previous = previous.getNext();
                current = previous.getNext();
            }
        }
    }

    public Object getFront() {
        if (start != null) {
            return start.getData();
        } else {
            return null;
        }
    }

    public void print() {
        Node current = start;

        if (current == null) {
            System.out.println("SingleLinkedList is Empty");
        }

        while (current != null) {
            System.out.print(current);
            current = current.getNext();
            if (current != null) {
                System.out.print(", ");
            }
        }
    }

    public int size() {
        int size = 0;

        Node current = start;

        while (current != null) {
            current = current.getNext();
            size++;
        }
        return size;
    }

    public Node getStart() {
        return this.start;
    }

    public Node getRear() {
        Node current = start;
        Node previous = current;
        while (current != null) {
            previous = current;
            current = current.getNext();
        }
        return previous;
    }
}

public class AddNumbersInSinglyLinkedList {
    public static void main(String[] args) {
        SinglyLinkedList listOne = new SinglyLinkedList();
        SinglyLinkedList listTwo = new SinglyLinkedList();
        listOne.addFront(5);
        listOne.addFront(1);
        listOne.addFront(3);
        listOne.print();
        System.out.println();
        listTwo.addFront(2);
        listTwo.addFront(9);
        listTwo.addFront(5);
        listTwo.print();
        SinglyLinkedList listThree = add(listOne, listTwo);
        System.out.println();
        listThree.print();
    }

    private static SinglyLinkedList add(SinglyLinkedList listOne, SinglyLinkedList listTwo) {
        SinglyLinkedList result = new SinglyLinkedList();
        Node startOne = listOne.getStart();
        Node startTwo = listTwo.getStart();
        int carry = 0;
        while (startOne != null || startTwo != null) {
            int one = 0;
            int two = 0;
            if (startOne != null) {
                one = (Integer) startOne.getData();
                startOne = startOne.getNext();
            }
            if (startTwo != null) {
                two = (Integer) startTwo.getData();
                startTwo = startTwo.getNext();
            }
            int sum = carry + one + two;
            carry = 0;
            if (sum > 9) {
                carry = sum / 10;
                result.addRear(sum % 10);
            } else {
                result.addRear(sum);
            }
        }
        return result;
    }
}

示例运行

Node:[Data=3], Node:[Data=1], Node:[Data=5]
Node:[Data=5], Node:[Data=9], Node:[Data=2]
Node:[Data=8], Node:[Data=0], Node:[Data=8]