题解 | #牛群的能量值#

牛群的能量值

https://www.nowcoder.com/practice/fc49a20f47ac431981ef17aee6bd7d15

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param l1 ListNode类 
     * @param l2 ListNode类 
     * @return ListNode类
     */
    public ListNode addEnergyValues (ListNode l1, ListNode l2) {
        // write code here
        ListNode result = new ListNode(-1);
        ListNode cur = result;
        int tempVal = 0;
        while(l1 != null && l2 != null){
            ListNode tempNode = new ListNode((l1.val + l2.val + tempVal) % 10);
            tempVal = (l1.val + l2.val + tempVal) / 10;
            cur.next = tempNode;
            cur = cur.next;
            l1 = l1.next;
            l2 = l2.next;
        }

        while(l1 == null && l2 != null){
            ListNode tempNode = new ListNode((l2.val + tempVal) % 10);
            tempVal = (l2.val + tempVal) / 10;
            cur.next = tempNode;
            cur = cur.next;
            l2 = l2.next;
        }

        while(l2 == null && l1 != null){
            ListNode tempNode = new ListNode((l1.val + tempVal) % 10);
            tempVal = (l1.val + tempVal) / 10;
            cur.next = tempNode;
            cur = cur.next;
            l1 = l1.next;
        }
        if(tempVal != 0){
            cur.next = new ListNode(tempVal);
        }
        
        return result.next;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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