leetcode 2. 两数相加
高精度类
import java.math.BigInteger;
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
BigInteger a,b;
ListNode p=l1;
StringBuilder sb=new StringBuilder();
while(true)
{
sb.append(p.val);
p=p.next;
if(p==null)break;
}
sb.reverse();
a=new BigInteger(sb.toString());
p=l2;
sb.setLength(0);
while(true)
{
sb.append(p.val);
p=p.next;
if(p==null)break;
}
sb.reverse();
b=new BigInteger(sb.toString());
a=a.add(b);
ListNode ans=null,tmp;
ans=new ListNode(a.mod(BigInteger.valueOf(10)).intValue(),null);
a=a.divide(BigInteger.valueOf(10));
tmp=ans;
while(a.compareTo(BigInteger.valueOf(0))!=0)
{
int t=a.mod(BigInteger.valueOf(10)).intValue();
a=a.divide(BigInteger.valueOf(10));
tmp.next=new ListNode(t,null);
tmp=tmp.next;
}
return ans;
}
}
模拟加法
import java.math.BigInteger;
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int t,c=0;
ListNode ans=null,tmp=null;
while(l1!=null||l2!=null)
{
t=0;
if(l1!=null)t+=l1.val;
if(l2!=null)t+=l2.val;
t+=c;
if(t>=10)
{
c=1;t-=10;
}
else c=0;
if(tmp==null)
{
tmp=new ListNode(t,null);
ans=tmp;
}
else{
tmp.next=new ListNode(t,null);
tmp=tmp.next;
}
if(l1!=null)l1=l1.next;
if(l2!=null)l2=l2.next;
}
if(c!=0)tmp.next=new ListNode(c,null);
return ans;
}
}