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

leetcode 2 Add Two Numbers

时间:2015-01-04 11:14:28      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode tn = null;
ListNode tl = new ListNode(0);
ListNode rl = tl;
int f = 0, s = 0, up = 0;
while (true) {

if (l1 != null) {
f = l1.val;
} else {
f = 0;
}

if (l2 != null) {
s = l2.val;
} else {
s = 0;
}

int sum = f + s + up;
if (sum < 10) {
tn = new ListNode(sum);
up = 0;
} else {
tn = new ListNode(sum%10);
up = 1;
}

tl.next = tn;
tl = tl.next;


if (l1 != null) {
l1 = l1.next;
}

if (l2 != null) {
l2 = l2.next;
}

if (l1 == null && l2 == null) {
if (up == 1) {
tn = new ListNode(up);
tl.next = tn;
}
break;
}
}

return rl.next;
}
}

技术分享

leetcode 2 Add Two Numbers

标签:

原文地址:http://www.cnblogs.com/aDreamer/p/4200431.html

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