马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
import java.math.BigInteger;
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode result = new ListNode(0);
ListNode head = result;
BigInteger x , y;
if(l1 == null && l2 == null){
return null;
}
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
x = new BigInteger(reverse(get_string(l1)));
y = new BigInteger(reverse(get_string(l2)));
x = x.add(y);
String a = reverse(x.toString());
int len = a.length();
for(int i = 0; i< len; i++){
Integer it = new Integer(a.substring(i,i+1));
result.next = new ListNode(it.intValue());
result = result.next;
}
return head.next;
}
public String get_string(ListNode l){
String re = "";
while(l != null){
re = re + l.val;
l = l.next;
}
return re;
}
public String reverse(String str){
String re = "";
int len = str.length();
for(int i = 0; i< len; i++){
re = str.substring(i,i+1) + re;
}
return re;
}
}
这个code 虽然可以通过,但是效率太低了,继续优化代码.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode result = new ListNode(0);
ListNode l = l1, j = l2, cur = result;
int digit = 0;
while(l != null || j != null){
int x = (l != null) ? l.val : 0;
int y = (j != null) ? j.val : 0;
int sum = digit + x + y;
digit = sum / 10;
ListNode nex = new ListNode(sum % 10);
cur.next = nex;
cur = cur.next;
if(l != null){
l = l.next;
}
if(j != null){
j = j.next;
}
}
if(digit > 0 ){
ListNode nex = new ListNode(digit);
cur.next = nex;
cur = cur.next;
}
return result.next;
}
}
nice job!
|