您的位置:首页 > 编程语言 > Java开发

[LeetCode-Java]2. Add Two Numbers

2016-09-24 16:41 344 查看
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

解:由于int大小限制,不可转化为int相加处理。对应位相加的过程中需注意末尾进位情况。

public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {

ListNode result = l1;

boolean flag = false;

while(true){

//对应位相加  考虑前一位的进位flag
l1.val = l1.val + l2.val + (flag?1:0);

//根据相加的结果  设置进位标志
if (l1.val >= 10){
l1.val = l1.val - 10;
flag = true;
}else {
flag = false;
}

if (l1.next == null || l2.next == null)  break;

l1 = l1.next;
l2 = l2.next;
}
//l2长度比较长,作相应处理
if (l1.next == null && l2.next != null){
l2 = l2.next;
l1.next = l2;

dealWithEnd(l2,flag);

}

//l1的长度比较长
if (l2.next == null && l1.next != null){
l1 = l1.next;
dealWithEnd(l1,flag);

}
//两者长度相同,需根据进位情况增加一个最高位
if (l1.next == null && l2.next == null){
if (flag) {
ListNode end = new ListNode(1);
l1.next = end;
}
}

return result;

}

//对附带进位信息的链表进行处理
static void dealWithEnd(ListNode listNode,Boolean flag){
while (true){
listNode.val  += (flag?1:0);

if (listNode.val >= 10){
listNode.val = listNode.val - 10;
flag = true;
}else {
flag = false;
break;
}

if (listNode.next == null){
if (flag) {
ListNode end = new ListNode(1);
listNode.next = end;
}
break;
}

listNode = listNode.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode