码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-09-09 13:52:16      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:log   list   sum   nod   inter   mos   amp   number   new   

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

标签:log   list   sum   nod   inter   mos   amp   number   new   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!