My JAVA 600ms solution, feel like it can be improved any thoughts?


  • 0
    L

    //Sorry that I am not good at using the very short statements and expressions; actually the logic is really //simple though it looks tedious

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
     //get the two number in string format ListNode l1 and l2 
     String n1 = "" + l1.val;
     while(l1.next != null){
    	n1 = n1 + l1.next.val;
    	l1 = l1.next;
     }
    
     String n2 = "" + l2.val;
     while(l2.next != null){
    	n2 = n2 + l2.next.val;
    	l2 = l2.next;
     }
    
     //n1, n2 are two strings; but append "0" to the shorter one so
     //n1 and n2 are now for example: "3425", "5500"
     int len1 = n1.length();
     int len2 = n2.length();
     int len = len1;
     if(len2 < len1){
    	int gap = len1 - len2;
    	String zeros = String.format("%0" + gap + "d", 0);
    	n2 = n2 + zeros;
     }
     if(len1 < len2){
    	len = len2;
    	int gap = len2 - len1;
    	String zeros = String.format("%0" + gap + "d", 0);
    	n1 = n1 + zeros;
     }
    
     //now add two numbers digit by digit
     int carryover = 0;
     String sumString = "";
     for(int i = 0; i < len; i++){		
    	int num1 = Character.getNumericValue(n1.charAt(i));
    	int num2 = Character.getNumericValue(n2.charAt(i));
    	int sum = num1 + num2 + carryover;
    	carryover = 0;
    	if(sum >= 10){
    		sum = sum % 10;
    		carryover = 1;
    	}
    	sumString = sumString + sum;
     }
     //append the final carryover if there is
      if(carryover == 1){
    	sumString = sumString + "1";
     }
    
     //now the sum of two number is ready but it's a string, so make it
     //as a list
     ListNode [] nodeArray = new ListNode[sumString.length()];
     for(int i = 0; i < sumString.length(); i++){
    	int value = Character.getNumericValue(sumString.charAt(i));
    	ListNode node = new ListNode(value);
    	nodeArray[i] = node;
     }
    
     for(int i = 0; i < nodeArray.length-1; i++){
    	 nodeArray[i].next = nodeArray[i+1];
     }
    
     //
     return nodeArray[0];        
    }

Log in to reply
 

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