两个超大的数相加

两个超大的数相加,当数的取值范围已经远远超过long型,可以将他们转化为字符串再相加,代码如下,用到了org.apache.commons.lang3.StringUtils类


import org.apache.commons.lang3.StringUtils;



public class BigNumberPlus {

public static String bigNumberPlus(String a,String b) {
int lenA = a.length();
int lenB = b.length();

if(lenA > lenB) {
b = StringUtils.leftPad(b,lenA,"0");
} else {
a = StringUtils.leftPad(a,lenB,"0");
}

int[] arrC = new int[a.length()+1];
for(int i=a.length()-1;i>=0;i--) {
int ai = Integer.parseInt(a.charAt(i)+"");
int bi = Integer.parseInt(b.charAt(i)+"");
int ci = arrC[i+1];
int t = ai+bi+ci;
arrC[i+1]=t%10;
arrC[i]=t/10;
}

StringBuffer str = new StringBuffer();
for(int i=0;i<arrC.length;i++) {
if(i==0 && arrC[i]==0) continue;
str.append(arrC[i]);
}

return str.toString();
}
public static void main(String[] args) {
String a = "985615478956321457896555214456358455617788885662489211024520211583312";
String b = "1574412369854631147823596334458552152385852121256121189655521445635845561077";
System.out.println(bigNumberPlus(a,b));
}
}
实现两个超大相加,可以使用链表来存储这两个。具体步骤如下: 1. 定义链表节点,包含一个值和指向下一个节点的指针。 ``` struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ``` 2.两个超大分别存储到两个链表中,每个节点存储一位字。 ``` ListNode *num1 = new ListNode(0); ListNode *num2 = new ListNode(0); ListNode *p1 = num1, *p2 = num2; for (int i = 0; i < len1; i++) { p1->val = num1_str[len1 - 1 - i] - '0'; if (i != len1 - 1) { p1->next = new ListNode(0); p1 = p1->next; } } for (int i = 0; i < len2; i++) { p2->val = num2_str[len2 - 1 - i] - '0'; if (i != len2 - 1) { p2->next = new ListNode(0); p2 = p2->next; } } ``` 其中,`num1_str`和`num2_str`为两个超大的字符串表示,`len1`和`len2`为它们的长度。 3.两个链表进行遍历,依次相加每一位,并将结果存储到新的链表中。 ``` ListNode *result = new ListNode(0); ListNode *p = result; int carry = 0; while (num1 || num2) { int sum = carry; if (num1) { sum += num1->val; num1 = num1->next; } if (num2) { sum += num2->val; num2 = num2->next; } p->val = sum % 10; carry = sum / 10; if (num1 || num2 || carry) { p->next = new ListNode(0); p = p->next; } } if (carry) { p->val = carry; } ``` 4. 将新的链表反转,得到相加后的结果。 ``` ListNode *rev_result = NULL; while (result) { ListNode *next = result->next; result->next = rev_result; rev_result = result; result = next; } ``` 最终,`rev_result`就是两个超大相加的结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值