Tuesday, September 10, 2013

Add two numbers@leetcode

刷题必备书籍Cracking the Coding Interview: 150 Programming Questions and Solutions 

简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
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
» Solve this problem

这题思路很简单,这个算法里很巧妙地用了当l1 or l2是null的时候用0来代替的做法,很简洁。

另外还要注意c++里面指针的运算,要新开辟node呢。


/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode *res=NULL, *tail=NULL;
ListNode *L1=l1, *L2=l2;
int carry=0;
int sum=0;
while(L1!=NULL||L2!=NULL||carry!=0)
{
int num1=(L1==NULL)? 0 :L1->val;
int num2=(L2==NULL)? 0 :L2->val;
sum=num1+num2+carry;
carry=sum/10;
sum%=10;
if(res==NULL)
{
res=new ListNode(sum);
tail=res;;
}
else
{
tail->next=new ListNode(sum);
tail=tail->next;
}
L1=(L1==NULL)? NULL :L1->next;
L2=(L2==NULL)? NULL :L2->next;
}
return res;
}
};
view raw add two numbers hosted with ❤ by GitHub

No comments:

Post a Comment

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...