刚刚我经历了可能是2017年3月22号的最大的大起大落。
2.
Add Two Numbers
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
想了半天才弄懂题目的意思,但是一眼就能看出怎么解啊,看了下居然是medium,抱着觉得整道题的难度就在读懂题目上的心态把代码写完了。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public String reverse(String s) {//借用别人的方法,自己实现过很多次了,懒得再写一次
int length = s.length();
if (length <= 1)
return s;
String left = s.substring(0, length / 2);
String right = s.substring(length / 2, length);
return reverse(right) + reverse(left);
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
String num1="";
while(l1!=null){
num1+=l1.val;
l1=l1.next;
}
String num2="";
while(l2!=null){
num2+=l2.val;
l2=l2.next;
}
num1=reverse(num1);
num2=reverse(num2);
int sum=Integer.parseInt(num1)+Integer.parseInt(num2);
String str=reverse(sum+"");
ListNode head=new ListNode(0);
ListNode now=head;
for(int i=0;i<str.length();i++){
if(i!=0){
now.next=new ListNode(0);
now=now.next;
}
now.val=Integer.parseInt(str.substring(i,i+1));
}
return head;
}
}
不要吐槽我用别人的轮子,这个轮子我造过不下五次了(呕
写完以后run code,一次通过默认给的Testcase,没有Runtime Error没有WA,卧槽还以为真的要一次通过了(too naive),结果submit了之后:
Submission Result: Runtime Error
Runtime Error Message:Line 34: java.lang.NumberFormatException: For input string: “9999999991”
Last executed input:
[9]
[1,9,9,9,9,9,9,9,9,9]
卧槽,居然有大于Integer.MAX_VALUE的数字,失算了;本来想用double做一次中转,后来想想治标不治本,超出了double的range还是个死字,于是决定不把数字转出来计算,直接在数组里相加。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry=0;
ListNode head=new ListNode(0);
ListNode now=head;
int i=0;
while((l1!=null)&&(l2!=null)){
if(i!=0){
now.next=new ListNode(0);
now=now.next;
}
int tmp=l1.val+l2.val+carry;
carry=0;
if(tmp>=10){
carry=tmp/10;
tmp%=10;
}
now.val=tmp;
l1=l1.next;
l2=l2.next;
i++;
}
while(l1!=null){
now.next=new ListNode(0);
now=now.next;
int tmp=l1.val+carry;
carry=0;
if(tmp>=10){
carry=tmp/10;
tmp%=10;
}
now.val=tmp;
l1=l1.next;
}
while(l2!=null){
now.next=new ListNode(0);
now=now.next;
int tmp=l2.val+carry;
carry=0;
if(tmp>=10){
carry=tmp/10;
tmp%=10;
}
now.val=tmp;
l2=l2.next;
}
if(carry!=0){
now.next=new ListNode(0);
now=now.next;
now.val=carry;
}
return head;
}
}
具体思路就是同位数字相加(两个链表中相同的位置就是相同的位,如果大于10就下一个位+1),当一个数组没了,另一个数组还有的话,就直接加那个有的数组(不过前面两个数组相加的进位要算上,不能漏掉)
顺便一提
每次看到Accepted,都感觉成就感爆棚了,之前花的时间也觉得值了。这个页面真的很好看啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊