Java: Overflow or wrong answer?


  • 0
    B

    I think my solution is right, but there's an overflow. Can someone confirm or help out?

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            System.out.println(getListNodeValue(l1));
            System.out.println(getListNodeValue(l2));
            int sum = getListNodeValue(l1) + getListNodeValue(l2);
            System.out.println(sum);
            List<Integer> list = new ArrayList<>();
            while(sum != 0) {
                int toAdd = sum % 10;
                list.add(toAdd);
                sum = sum / 10;   
            }
            
            if (list.size() == 0) {
                return new ListNode(0);
            }
            
            ListNode toReturn = null;
            ListNode toSet = null;
            for (int i = 0; i <  list.size(); i++) {
                if (toReturn == null) {
                    toReturn = new ListNode(list.get(i));
                    toSet = toReturn;
                } else {
                    toSet.next = new ListNode(list.get(i));
                    toSet = toSet.next;
                }
            }
            return toReturn;
        }
        
        private int getListNodeValue(ListNode listNode) {
            int sum = 0;
            int count = 0;
            while (listNode != null) {
                double temp = listNode.val * Math.pow(10, count);
                System.out.println(temp);
                sum = (int)(sum + temp);
                count = count + 1;
                listNode = listNode.next;
            }
            return sum;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.