Naive approach - converting linkedList into int and viceversa - why doesn't it work?


  • 0
    B
    /**
     * 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) {
            int n1 = IntOfList(l1);
            int n2 = IntOfList(l2);
            int n3 = n1+n2;
            return ListOfInt(n3);
        }
        public int IntOfList(ListNode l) {
            if (l.next == null) {
                return l.val;
            }
            else {
                return l.val + 10*IntOfList(l.next);
            }
        }
        public ListNode ListOfInt(int n) {
            ListNode l = new ListNode(0);
            if (n > 0) {
                l.val = n%10;
                int q = (n - n%10)/10;
                if (q>0) {
                    l.next = ListOfInt(q);
                }
            }
            return l;
        }
    }

  • 0

    Isn't it clear from the Input/Output/Expected which you failed?


  • 0
    N

    integer overflow.

    try unsigned long.


Log in to reply
 

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