Add Two Numbers (C++) refactored

Realized I could make it even cleaner. Changed the while loop condition which makes the code much cleaner gets rid of some unnecessary code.

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(l1 || l2 || bCarry) {
    sum = 0;
    if (l1) {
      sum += l1->val;
      l1 = l1->next;
    }
    if (l2) {
      sum += l2->val;
      l2 = l2->next;
    }
    if (bCarry) {
      sum += 1;
      bCarry = false;
    }
    if (!result)
      result = tail = new ListNode(sum%10);
    else {
      tail->next = new ListNode(sum%10);
      tail = tail->next;
    }
    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