zoukankan      html  css  js  c++  java
  • 【Leetcode】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

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
    12         ListNode *p1 = l1, *p2 = l2, dummy(-1), *tail = &dummy;
    13         int sum = 0, carry = 0;
    14         while (p1 != nullptr || p2 != nullptr) {
    15             int v1 = p1 == nullptr ? 0 : p1->val;
    16             int v2 = p2 == nullptr ? 0 : p2->val;
    17             p1 = p1 == nullptr ? nullptr : p1->next;
    18             p2 = p2 == nullptr ? nullptr : p2->next;
    19 
    20             sum = v1 + v2 + carry;
    21             tail->next = new ListNode(sum % 10);
    22             tail = tail->next;
    23             carry = sum / 10;
    24         }
    25         if (carry > 0) {
    26             tail->next = new ListNode(carry);
    27             tail = tail->next;
    28         }
    29         return dummy.next;
    30     }
    31 };
    View Code

    Add binary类似,思想与方法完全一样,只是用链表实现,在链表前加哑元素可以使尾插入的代码简化。

  • 相关阅读:
    Django入门
    RCNN 研究相关
    [Android UI]View滑动方式总结
    [Android UI]View基础知识
    [Android]Android开发艺术探索第1章笔记
    [Leetcode]017. Letter Combinations of a Phone Number
    java之this关键字
    POJ 1000 A+B
    [Leetcode]016. 3Sum Closest
    [Leetcode]015. 3Sum
  • 原文地址:https://www.cnblogs.com/dengeven/p/3613504.html
Copyright © 2011-2022 走看看