Self-documenting recursive solution using BigInteger


  • 0
    L
    import java.math.BigInteger;
    
    /**
     * 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) {
            return bigIntegerToNodeNumber(nodeNumberToBigInteger(l1).add(nodeNumberToBigInteger(l2)));
        }
        
        private String nodeNumberToString(ListNode listNodeNumber) {
            return nodeNumberToString(listNodeNumber, "");
        }
        
        private String nodeNumberToString(ListNode listNodeNumber, String baseString) {
            String newBaseString = listNodeNumber.val + baseString;
            
            if (listNodeNumber.next == null) {
                System.out.println("Created string from node number: " + newBaseString);
                return newBaseString;
            } else {
                return nodeNumberToString(listNodeNumber.next, newBaseString);
            }
        }
        
        
        private BigInteger nodeNumberToBigInteger(ListNode listNodeNumber) {
            return new BigInteger(nodeNumberToString(listNodeNumber));
        }
        
        
        private ListNode bigIntegerToNodeNumber(BigInteger n) {
            return stringToNodeNumber(n.toString());
        }
        
        private ListNode stringToNodeNumber(String stringNumber) {
            return stringToNodeNumber(null, stringNumber);
        }
        
        private ListNode stringToNodeNumber(ListNode runningList, String stringNumber) {
            char firstCharacter = stringNumber.charAt(0);
            int firstNumber = Character.getNumericValue(firstCharacter);
            
            String newStringNumber = stringNumber.substring(1, stringNumber.length());
            ListNode newNode = new ListNode(firstNumber);
            
            newNode.next = runningList;
            
            if (newStringNumber.length() > 0) {
                return stringToNodeNumber(newNode, newStringNumber);
            } else {
                return newNode;
            }
        }
    }
    

Log in to reply
 

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