Algorithm:
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
package com.util.main;
import com.tuniu.ngsp.nws.support.util.JsonExceptionUtil;
public class AddTwoNumbers {
public static class ListNode{
private int value;
private ListNode next;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
public ListNode(int value) {
this.value = value;
}
public ListNode(int value,ListNode ln){
this.value=value;
this.next=ln;
}
}
public static ListNode addTwoNumbers(ListNode l1,ListNode l2){
ListNode head = new ListNode(0);
//cur可能认为是一个指针,总是指向末节点的next
ListNode p = l1,q = l2,cur = head;
int carry = 0;
while(p!=null || q!=null){
int x = (p!=null?p.getValue():0);
int y = (q!=null?q.getValue():0);
int sum = carry + x + y;
//进位数
carry = sum/10;
//当前位的和
cur.next = new ListNode(sum%10);
cur = cur.next;
if(p!=null){
p = p.next;
}
if(q!=null){
q = q.next;
}
if(carry>0){
cur.next = new ListNode(carry);
}
}
return head.next;
}
public static void main (String[] args){
ListNode l1a = new ListNode(3);
ListNode l1b = new ListNode(4,l1a);
ListNode l1 = new ListNode(2,l1b);
ListNode l2a = new ListNode(4);
ListNode l2b = new ListNode(6,l2a);
ListNode l2 = new ListNode(5,l2b);
ListNode sum = addTwoNumbers(l1,l2);
System.out.println(JsonExceptionUtil.toString(sum));
}
}
Review
https://apenwarr.ca/log/20190318
讲述语言的变迁路程,因为算是半路入行,当时先做的vb,感觉没啥前途,java使用广泛就直接学习java了,对语言的发展变迁并没有去了解过,阅读了此篇文章对语言之间的关系有了一个比较宽泛的了解,具体因为没使用过所以还是比较糊的
Tips
java8 map新特性
Share
消息中间件消费到的消息处理失败怎么办?
博客分享了算法问题,即两个逆序链表表示的非负整数相加;回顾了语言变迁文章,让人对语言关系有宽泛了解;介绍了Java 8 map的新特性getOrDefault;还分享了消息中间件消费消息处理失败的相关文章链接。
1924

被折叠的 条评论
为什么被折叠?



