题解 | #牛群的能量值#
牛群的能量值
https://www.nowcoder.com/practice/fc49a20f47ac431981ef17aee6bd7d15
知识点:链表 模拟 大整数加法
思路:正常的链表实现大整数加法,维护进位值p,
编程语言:java
如果我的思路启发了你,给个小小关注吧~
我是废江,一个从java跑到内核再准备润回java的打工人,我会持续分享从linux内核到上层java微服务等干货
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 l3 = new ListNode(-1); ListNode cur = l3; int p = 0; while (l1 != null && l2 !=null){ ListNode tmp = new ListNode((l1.val + l2.val + p) % 10); tmp.next = null; cur.next = tmp; cur = tmp; p = (l1.val + l2.val + p) / 10; l1 = l1.next; l2 = l2.next; } //当链表遍历完,别忘记了还有进位值p,假设p=1,恰好剩下的链表是9,就不能直接拼接 if(p == 1){ while (l1 != null){ ListNode tmp = new ListNode((l1.val + p) %10); tmp.next = null; cur.next = tmp; cur = tmp; p = (l1.val + p) / 10; l1 = l1.next; } while (l2 != null){ ListNode tmp = new ListNode((l2.val + p) %10); tmp.next = null; cur.next = tmp; cur = tmp; p = (l2.val + p) / 10; l2 = l2.next; } }else cur.next = l1 != null ? l1 : l2; if(p == 1){ cur.next = new ListNode(1); cur.next.next =null; } return l3.next; } }