https://leetcode-cn.com/problems/add-two-numbers/description/
今年春招时,我学长被问到这道题,明明是一道简单得一匹的题,但HR的语言表达能力实在是让人无力吐槽,这让我对明年的春招表示有点haipia。
思路:用链表模拟两个数字加法,注意一下进位以及加位的情况就好了。
我刚刚开始用JAVA,写的代码自己看着都觉得丑……(逃
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode l3 = null;
ListNode tmp = null;
int up = 0;
while(l1 != null || l2 != null) {
int cnt = up;
up = 0;
if(l1 != null) {
cnt = cnt + l1.val;
l1 = l1.next;
}
if(l2 != null) {
cnt = cnt + l2.val;
l2 = l2.next;
}
if(cnt >= 10) {
up = 1;
cnt = cnt % 10;
}
if(l3 == null) {
l3 = new ListNode(cnt);
tmp = l3;
}
else {
tmp.next = new ListNode(cnt);
tmp = tmp.next;
}
}
if(up != 0) {
tmp.next = new ListNode(up);
}
return l3;
}
}