美文网首页
LeetCode-Add Two Numbers

LeetCode-Add Two Numbers

作者: CocoaJason | 来源:发表于2019-04-11 16:06 被阅读0次

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

相关文章

网友评论

      本文标题:LeetCode-Add Two Numbers

      本文链接:https://www.haomeiwen.com/subject/hftxwqtx.html