zoukankan      html  css  js  c++  java
  • Add Two Numbers

    1557 / 1558 test cases passed.只有一个样例没有通过,应该是越界的问题,暂时不管了,这道题一开始按照自己的思路来,然后就浪费了一上午的时间,后面觉得还是得参考别人的思路,看了别人的解答后,发现自己智商还是挺lower的,只会用最简单的方法来做,而没有一丝创造性;现在贴出代码,算法的思路主要是利用了两个函数,一个是链表转为long 整形,另一个是long 整形转为链表。其中用队列来操作好像挺符合的,代码如下:

    class Solution
    {
    public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
    {
    long a=listtolong(l1);
    long b=listtolong(l2);
    long sum=a+b;
    return longtolist(sum);
    }

    long listtolong(ListNode* t1)
    {
    queue<unsigned long long>b;
    long sum = 0;
    long temp = 1;
    while (t1!=NULL)
    {
    b.push(t1->val);
    t1 = t1->next;
    }
    while (b.size()!=0)
    {
    sum = sum + b.front()*temp;
    temp = temp * 10;
    b.pop();
    }
    return sum;
    }


    ListNode* longtolist(long t)
    {
    queue<unsigned long long>c;
    while (t!=0)
    {
    c.push(t%10);
    t = t / 10;
    }
    ListNode* t2 = new ListNode(0);
    ListNode* t1 = t2;
    while (c.size()!=0)
    {
    t2->val = c.front();
    c.pop();
    if (c.size() != 0)
    {
    ListNode* t3 = new ListNode(0);
    t2->next = t3;
    t2 = t3;
    }
    }
    return t1;
    }
    };

  • 相关阅读:
    线程
    开启程序子进程的方式
    multiprocess模块
    计算机网络小知识
    解决粘包问题
    网络编程相关
    反射与元类
    多态相关
    封装相关与接口
    类的继承和组合
  • 原文地址:https://www.cnblogs.com/a-dreaming-dreamer/p/5740930.html
Copyright © 2011-2022 走看看