You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
@interface ListNode : NSObject
@property (nonatomic, assign ) NSInteger value;
@property (nonatomic, strong ) ListNode *next;
@end
@implementation ListNode
+ (instancetype)listWithValue:(NSInteger)value
next:(ListNode *)next{
ListNode *node = [ListNode new];
node.value = value;
node.next = next;
return node;
}
@end
- (ListNode *)addTwoNumbersWithList:(ListNode *)listFirst
list:(ListNode *)listLast{
ListNode *tempNode = [ListNode listWithValue:-1 next:nil];
ListNode *cur = tempNode;
NSInteger carry = 0;
while (listFirst != nil || listLast != nil) {
NSInteger v1 = listFirst.value;
NSInteger v2 = listLast.value;
NSInteger sum = v1 + v2 + carry;
carry = sum / 10;
cur.next = [ListNode listWithValue:sum % 10 next:nil];
cur = cur.next;
if (listFirst) {
listFirst = listFirst.next;
}
if (listLast) {
listLast = listLast.next;
}
}
if (carry == 1) {
cur.next = [ListNode listWithValue:1 next:nil];
}
return tempNode.next;
}
ListNode *three = [ListNode listWithValue:3 next:nil];
ListNode *four = [ListNode listWithValue:4 next:three];
ListNode *two = [ListNode listWithValue:2 next:four];
ListNode *six = [ListNode listWithValue:6 next:four];
ListNode *five = [ListNode listWithValue:5 next:six];
ListNode *node = [self addTwoNumbersWithList:five list:two];
while (node.next) {
NSLog(@"%ld",node.value);
node = node.next;
}
2019-04-11 15:57:29.347297+0800 Test[40798:1579348] 7
2019-04-11 15:57:29.347574+0800 Test[40798:1579348] 0
2019-04-11 15:57:29.347715+0800 Test[40798:1579348] 8
网友评论