March 31, 2013

  • http://leetcode.com/onlinejudge#question_2
    Add two numbers
    =.=....
    甚至唔係考algorithm...只係考我寫code者,都搞左我一輪先寫到出黎=.=....
    平時寫下MVC 既controller真係太簡單...

    同埋你睇我D code幾鬼,連個while loop都用得唔好
    竟然會有少少code duplicate左

    xanga真係好鬼事diu but, 完全show唔到indentation

    package west;

    public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    // Count the length of lists.
    // Assign the shorter list to the short list.
    int length1 = countlength(l1);
    int length2 = countlength(l2);
    ListNode shortlist;
    ListNode longlist;
    if (length1 < length2) {
    shortlist = l1;
    longlist = l2;
    } else {
    shortlist = l2;
    longlist = l1;
    }
    // Start adding two list.
    // loop the shorter list first
    ListNode nextnode;
    Boolean carry = false;
    ListNode prevnode = new ListNode((shortlist.val + longlist.val+ (carry?1:0)) % 10) ;
    ListNode resultlist = prevnode;
    carry = (shortlist.val + longlist.val + (carry?1:0)) > 9;
    while (shortlist.next != null){
      shortlist = shortlist.next;
      longlist = longlist.next;
      nextnode = new ListNode((shortlist.val + longlist.val + (carry?1:0)) % 10) ;
      carry = (shortlist.val + longlist.val + (carry?1:0)) > 9;
      prevnode.next = nextnode;
      prevnode = nextnode;
    }
    // loop the remaining part of the longer list
    while (longlist.next != null){
      longlist = longlist.next;
      nextnode = new ListNode((longlist.val + (carry?1:0)) % 10);

    carry = (longlist.val + (carry?1:0)) > 9;
    prevnode.next = nextnode;
    prevnode = nextnode;
    }
    // check if there is any remaining carry
    if (carry){
    nextnode = new ListNode(1);
    prevnode.next = nextnode;
    prevnode = nextnode;
    }
    return resultlist;
    }
    int countlength(ListNode l){
      int i = 1;
      while (l.next != null) {i++; l = l.next;}
      return i;
    }
    }

Recent Posts

Recent Comments

Categories