105人阅读 评论(0)

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

import java.math.BigInteger;

public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
BigInteger num1 = BigInteger.ZERO;
BigInteger num2 = BigInteger.ZERO;
BigInteger temp = BigInteger.ONE;

while(l1!=null) {
//num1+=temp*l1.val;
temp=temp.multiply(BigInteger.TEN);
l1=l1.next;
}
temp=BigInteger.ONE;
while(l2!=null) {
temp=temp.multiply(BigInteger.TEN);
l2=l2.next;
}
if(sum.compareTo(BigInteger.ZERO)==0)
return new ListNode(0);
else {
ListNode l = new ListNode(sum.mod(BigInteger.TEN).intValue());
ListNode p=l;
while(sum.compareTo(BigInteger.ZERO)!=0) {
sum=sum.divide(BigInteger.TEN);
if(sum.compareTo(BigInteger.ZERO)!=0) {
p.next = new ListNode(sum.mod(BigInteger.TEN).intValue());
p=p.next;
}
}
return l;
}
}
}

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* result = l1 ? l1 : l2;
struct ListNode* carry = l1 ? l2 : l1;
struct ListNode* node = result;
struct ListNode* tmp;
int c = 0;
int s;
while (l1 || l2) {
s = c;
if (l1) { s += l1->val; l1=l1->next; }
if (l2) { s += l2->val; l2=l2->next; }
c = s > 9 ? 1 : 0;
node->val = c ? s - 10 : s;
if (l1) {
node = node->next = l1;
} else if (l2) {
node = node->next = l2;
} else {
node->next = NULL;
}
}
if (c) {
carry->val = c;
node->next = carry;
node = node->next;
}
node->next = NULL;
return result;
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：64351次
• 积分：3285
• 等级：
• 排名：第10717名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：8条
文章分类
阅读排行
最新评论