Add Two Numbers (C++)

This is from the http://www.ihas1337code.com/onlinejudge website.  His onlinejudge testing is really neat. I’d like to setup something like that.

// Definition for singly-linked list.
// DO NOT modify this.
struct ListNode {
  int val;
  ListNode *next;
  ListNode(int x) : val(x), next(NULL) {}
};

ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
  // Start typing your C/C++ solution below
  // DO NOT write int main() function
  // NO #include's are required

  bool bCarry = false;
  ListNode *result = NULL, *tail = NULL;
  int sum = 0;

  while(true) {
    // No more values so break out of loop and check carry
    if (!l1 && !l2) {
      if (bCarry) {
        tail->next = new ListNode(1);
      }
      break;
    }
    // Values in list
    if (l1 || l2) {
      sum = 0;
      // Check list 1
      if (l1) {
        sum += l1->val;
        l1 = l1->next;
      }
      // Check list 2
      if (l2) {
        sum += l2->val;
        l2 = l2->next;
      }
      // Add carry bit
      if (bCarry) {
        sum += 1;
        bCarry = false;
      }
      // Add to result list
      if (!result)
        result = tail = new ListNode(sum%10);
      else {
        tail->next = new ListNode(sum%10);
        tail = tail->next;
      }
      // Calculate carry
      bCarry = (sum >= 10) ? true : false;
    }

  }
  return result ;

}
Advertisements
This entry was posted in Coding and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s