您的位置:首页 > 其它

Leetcode日记(2)---Add two numbers

2015-12-01 17:42 357 查看


题目详解

两数相加,进位的处理,譬如7+8之后,获取和的个位数字和十位数字

问题追踪



查找了null的头文件,查询了cplusplus,头文件为stddef.h

#include<stddef.h>

using namespace std;

struct ListNode{
int val;
ListNode *next;
ListNode(int x):val(x), next(NULL){}
};

class Solution{
public:
ListNode *addTwoNumbers(ListNode  *l1 , ListNode  *l2){
int carry = 0;
ListNode* tail = new ListNode(0);  // kai shi lian biao shi shu zi wei 0 de lian biao
ListNode* ptr = tail;

while(l1 != NULL || l2 != NULL){
int val1=0;
if(l1 != NULL){
val1 = l1->val;
l1 = l1 ->next;
}

int val2 = 0;
if(l2 != NULL){
val2 = l2->val;
l2 = l2 ->next;
}

int tmp = val1 + val2 +carry;
ptr->next = new ListNode(tmp % 10) ;  // zhi liu xia ge wei shu zi
carry = tmp /10 ;
ptr = ptr ->next;
}

if (carry == 1){
ptr->next = new ListNode(1);
}

return tail->next;

}
};

int main(){
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: