题解 | #牛群的能量值#

牛群的能量值

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
        int carry = 0;
        auto phead = new ListNode(-1);
        phead ->next = nullptr;
        auto cur = phead;
        while(l1 && l2){
            int temp = l1->val + l2->val + carry;
            carry = temp / 10;
            cur ->next = new ListNode(temp%10);
            cur = cur->next;
            l1 = l1->next;
            l2 = l2->next;
        }
        while(l1){
            int temp = l1->val + carry;
            carry = temp / 10;
            cur ->next = new ListNode(temp%10);
            cur = cur ->next;
            l1 = l1->next;
        }
        while(l2){
            int temp = l2->val + carry;
            carry = temp / 10;
            cur ->next = new ListNode(temp%10);
            cur = cur ->next;
            l2=l2->next;
        }
        if(carry!=0)
            cur ->next = new ListNode(carry);
        return phead->next;
    }
};

全部评论

相关推荐

06-19 13:40
武汉大学 Java
点赞 评论 收藏
分享
如题
投递阿里巴巴集团等公司10个岗位 >
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务