# 【LeetCode】两数相加

## 题目描述

```输入：(2 -> 4 -> 3) + (5 -> 6 -> 4)

## 题目解析

### 翻车尝试1：虾扯蛋法

```class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head1 = l1;
ListNode head2 = l2;
int i = 0;
int j = 0;
int index = 0;
// 将链表l1转化为整数
while (head1 != null) {
i += head1.val * Math.pow(10, index);
index++;
head1 = head1.next;
}
index = 0;
// 将链表l2转化为整数
while (head2 != null) {
j += head2.val * Math.pow(10, index);
index++;
head2 = head2.next;
}
int sum = i + j;
ListNode newHead = new ListNode(0);
ListNode tmpHead = newHead;
int sign = 0;
// 将结果转化为链表
while (sum > 0 || sign == 0) {
int tmp = sum % 10;
sum = sum / 10;
tmpHead.next = new ListNode(tmp);
tmpHead = tmpHead.next;
sign++;
}
return newHead.next;
}
}```

```输入：
[9]
[1,9,9,9,9,9,9,9,9,9]

[0]

[0,0,0,0,0,0,0,0,0,0,1]```

### 翻车尝试2：虾扯蛋升级法

```class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head1 = l1;
ListNode head2 = l2;
long i = 0;
long j = 0;
long index = 0;
while (head1 != null) {
i += head1.val * Math.pow(10, index);
index++;
head1 = head1.next;
}
index = 0;
while (head2 != null) {
j += head2.val * Math.pow(10, index);
index++;
head2 = head2.next;
}
long sum = i + j;
ListNode newHead = new ListNode(0);
ListNode tmpHead = newHead;
int sign = 0;
while (sum > 0 || sign == 0) {
int tmp = (int)(sum % 10);
sum = sum / 10;
tmpHead.next = new ListNode(tmp);
tmpHead = tmpHead.next;
sign++;
}
return newHead.next;
}
}```

### 翻车尝试3：虾扯蛋终极法

```class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head1 = l1;
ListNode head2 = l2;
BigInteger i = new BigInteger(0);
BigInteger j = new BigInteger(0);
long index = 0;
while (head1 != null) {
i.add(BigInteger.valueOf(head1.val * Math.pow(10, index)));
index++;
head1 = head1.next;
}
index = 0;
while (head2 != null) {
j.add(BigInteger.valueOf(head2.val * Math.pow(10, index)));
index++;
head2 = head2.next;
}
BigInteger sum = i.add(j);
ListNode newHead = new ListNode(0);
ListNode tmpHead = newHead;
int sign = 0;
while (sum.compareTo(0) == 1 || sign == 0) {
int tmp = sum.mod(10).intValue();
sum = sum.divide(10);
tmpHead.next = new ListNode(tmp);
tmpHead = tmpHead.next;
sign++;
}
return newHead.next;
}
}```

## 常规解法

```[9]
[1,9,9,9,9,9,9,9,9,9]```

```class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head1 = l1;
ListNode head2 = l2;
ListNode newHead = new ListNode(0);
ListNode head3 = newHead;
// 进位标志
boolean carry = false;
while (head1 != null || head2 != null) {
// 获取对应位置的值然后相加
int x = (head1 != null) ? head1.val : 0;
int y = (head2 != null) ? head2.val : 0;
int sum = carry ? (x + y + 1) : (x + y);
// 处理进位
if (sum >= 10){
sum -= 10;
carry = true;
} else {
carry = false;
}
// 新增节点
head3.next = new ListNode(sum % 10);
head3 = head3.next;
if (head1 != null) head1 = head1.next;
if (head2 != null) head2 = head2.next;
}
if (carry) {
head3.next = new ListNode(1);
}
return newHead.next;
}
}```

104 篇文章49 人订阅

0 条评论