Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create add two numbers #100

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
57 changes: 57 additions & 0 deletions C++/add two numbers
@@ -0,0 +1,57 @@
// Source : https://oj.leetcode.com/problems/add-two-numbers/
/**********************************************************************************
*
* You are given two linked lists representing two non-negative numbers.
* The digits are stored in reverse order and each of their nodes contain a single digit.
* Add the two numbers and return it as a linked list.
*
* Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
* Output: 7 -> 0 -> 8
*
**********************************************************************************/

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {

public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
int x=0, y=0, carry=0, sum=0;
ListNode *h=NULL, **t=&h;

while (l1!=NULL || l2!=NULL){
x = getValueAndMoveNext(l1);
y = getValueAndMoveNext(l2);

sum = carry + x + y;

ListNode *node = new ListNode(sum%10);
*t = node;
t = (&node->next);

carry = sum/10;
}

if (carry > 0) {
ListNode *node = new ListNode(carry%10);
*t = node;
}

return h;
}
private:
int getValueAndMoveNext(ListNode* &l){
int x = 0;
if (l != NULL){
x = l->val;
l = l->next;
}
return x;
}
};