首页 > 其他 > 详细

Leetcode刷题总结: 445. Add Two Numbers II

时间:2017-09-09 13:26:18      阅读:298      评论:0      收藏:0      [点我收藏+]

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7

 

思路一:

题目说了代表两个int型的数,第一个思路是我直接将这个list转成int型的正整数, 然后两个int型相加,为了防止溢出,用long存储sum;

再将sum转换成list;

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    unsigned int getNum(ListNode *pnode) {
        unsigned int result = 0;
        while(pnode != NULL) {
            result = result*10 + pnode->val;
            pnode = pnode->next;
        }
        return result;
    }
    
    ListNode* transNumToList(long num) {
        ListNode *cur = new ListNode(num%10);
        num = num/10;
        while (num > 0) {
            int res = num%10;
            num /= 10;
            ListNode *pnew = new ListNode(res);
            pnew->next = cur;
            cur = pnew;
        }
        return cur;
        
    }
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        unsigned int num1 = getNum(l1);
        unsigned int num2 = getNum(l2);
        cout << num1 << endl;
        cout << num2 << endl;
        unsigned long sum = num1+num2;
        return transNumToList(sum);
    }
};

  

 

 

 

Leetcode刷题总结: 445. Add Two Numbers II

原文:http://www.cnblogs.com/syjbupt/p/7497929.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!