题目要求
-
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
-
请你将两个数相加,并以相同形式返回一个表示和的链表。
-
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
-
每个链表中的节点数在范围 [1, 100] 内
-
0 <= Node.val <= 9
-
题目数据保证列表表示的数字不含前导零
一、我自己的解法(暴力解)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public int getLength(ListNode listNode) {
int i = 1;
while (listNode.next != null) {
i++;
listNode = listNode.next;
}
return i;
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int l1Length = getLength(l1);
int l2Length = getLength(l2);
int middle = Math.max(l1Length, l2Length) - Math.min(l1Length, l2Length);
int add = 0; //进位
StringBuilder nums = new StringBuilder("");
int shortLength = Math.min(l1Length, l2Length);
for (int i = shortLength; i > 0; i--) {
int num = l1.val + l2.val+add;
if (num>=10){
add = 1;
nums.append(num-10);
}else{
add = 0;
nums.append(num);
}
l1=l1.next;
l2=l2.next;
}
ListNode longNode = l1Length>l2Length?l1:l2;
if (middle >= 0){
for (int i = 0; i < middle; i++) {
int a = longNode.val+add;
if (a>=10){
add = 1;
nums.append(a-10);
}else{
add = 0;
nums.append(a);
}
longNode=longNode.next;
}
if (add == 1){
nums.append(1);
}
}
String s = nums.toString();
ListNode ll1 = new ListNode(Integer.parseInt(s.substring(0, 1)), null);
int y = 1;
ListNode tem = ll1;
while (y < s.length()) {
tem.next = new ListNode(Integer.parseInt(s.substring(y, y + 1)), null);
tem = tem.next;
y += 1;
}
return ll1;
}
}
二、比较好的解法
public class B_Solution {
public static void main(String[] args) {
}
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
int sum = 0; //结果
int more = 0; //进位
ListNode pre = dummy;
while (l1 != null || l2 != null || more > 0){
sum = (l1 == null?0:l1.val) + (l2 == null?0:l2.val) + more;
more = sum / 10; //判断有无进位
sum %= 10; //如果大于10,就进上去了,留下余数
ListNode node = new ListNode(sum); //新的一个节点,存储计算出来的值
pre.next = node; //把他替换为这个新的节点
pre = node;
l1 = l1 == null ? null : l1.next;
l2 = l2 == null ? null : l2.next;
}
return dummy.next;
}
}