zoukankan      html  css  js  c++  java
  • LeetCode 0、《两数相加》

    一、给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。

    你可以假设除了数字 0 之外,这两个数字都不会以零开头。

    示例:

    输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
    输出:7 -> 0 -> 8
    原因:342 + 465 = 807

    -----------------------------------------------------------
    1、定义一个链表

    class LinkedListNode
    {
      public object Value;
      public LinkedListNode Next;

      public LinkedListNode()
      {
        this.Value = null;
        this.Next = null;
      }

      public LinkedListNode(int value)
      {
        this.Value = value;
        this.Next = null;
      }
    }

     

    public static LinkedListNode AddTwoNumber(LinkedListNode n1, LinkedListNode n2)
    {
      LinkedListNode ret = new LinkedListNode();
      LinkedListNode cur = ret;
      int carry = 0;
      int sum;

      while (n1 != null || n2 != null)
      {
        sum = (n1 == null ? 0 : (int)n1.Value) + (n2 == null ? 0 : (int)n2.Value) + carry;
        carry = sum / 10;
        cur.Value = sum % 10;

        if (n1 != null)
          n1 = n1.Next;
        if (n2 != null)
          n2 = n2.Next;

        cur.Next = new LinkedListNode();
        cur = cur.Next;
      }

      if (carry == 1)
        cur.Next = new LinkedListNode(1);

      return ret;
    }

     

    调用

    LinkedListNode n1 = new LinkedListNode(2);
    n1.Next = new LinkedListNode(4);
    n1.Next.Next= new LinkedListNode(3);

    LinkedListNode n2 = new LinkedListNode(5);
    n2.Next = new LinkedListNode(6);
    n2.Next.Next = new LinkedListNode(8);

    LinkedListNode nk = AddTwoNumber(n1, n2);

  • 相关阅读:
    Linux:mv命令
    Linux:cp -rp
    Linux:sed命令
    Linux:cut命令...未完待续
    Linux:xargs命令
    python动态获取对象的属性和方法 (转载)
    python 继承中的super
    HTTP认证机制(翻译)
    技术名词解释
    设计模式之代理模式
  • 原文地址:https://www.cnblogs.com/coderblog/p/9145077.html
Copyright © 2011-2022 走看看