题解 | #牛群的能量值#
牛群的能量值
https://www.nowcoder.com/practice/fc49a20f47ac431981ef17aee6bd7d15
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param l1 ListNode类
* @param l2 ListNode类
* @return ListNode类
*/
ListNode* addEnergyValues(ListNode* l1, ListNode* l2) {
// write code here
if (l1 == nullptr) return l2;
if (l2 == nullptr) return l1;
ListNode* res = new ListNode(-1);
ListNode* cur = res;
int a = 0;
while (l1 || l2) {
int value1 = l1 ? l1->val : 0;
int value2 = l2 ? l2->val : 0;
int sum = value1 + value2 + a;
cur->next = new ListNode(sum % 10);
a = sum / 10;
cur = cur->next;
if (l1) l1 = l1->next;
if (l2) l2 = l2->next;
}
if (a) {
cur->next = new ListNode(a);
}
return res->next;
}
};
