题解 | #牛群的能量值#
牛群的能量值
https://www.nowcoder.com/practice/fc49a20f47ac431981ef17aee6bd7d15
依次遍历链表,将元素相加之后的值依次添加到新的链表当中。如果最后还剩进位,那么还需要继续建立节点存储。
import java.util.*;
public class Solution {
public ListNode addEnergyValues (ListNode l1, ListNode l2) {
// 合并到新的链表中去
ListNode head = new ListNode(0);
ListNode cur = head;
int upper = 0; // 记录进位
int num = 0;
int x,y;
while(l1 != null || l2 != null){
x = l1 != null ? l1.val : 0;
y = l2 != null ? l2.val : 0;
num = (x + y + upper) % 10;
upper = (x + y + upper) / 10;
cur.next = new ListNode(num);
cur = cur.next;
if(l1!=null) l1 = l1.next;
if(l2!=null) l2 = l2.next;
}
// 检查是否还有进位
if(upper > 0) cur.next = new ListNode(1);
return head.next;
}
}
传音控股公司福利 356人发布