题目描述:请设计一个算法完成两个超长正整数的加法。 要求实现函数: void AddLongInteger(char * pcAddend, char * pcAugend, char * pcAddResult); 输入参数: char * pcAddend:加数 char * pcAugend:被加数 char * pcAddResult:加法结果 返回值:无 | |
运行时间限制: | 1 Sec |
内存限制: | 128 MByte |
输入: | 两个超长正整数的字符串 |
输出: | 相加后结果的字符串 |
样例输入: | 123456789123456789 123456789123456789 |
样例输出: | 246913578246913578 |
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
char[] a1 = sc.next().toCharArray();
char[] a2 = sc.next().toCharArray();
char[] result = AddLongInteger(a1,a2);
for(int i = 0;i < result.length;i++){
System.out.print(result[i]);
}
}
/*
* AddLongInteger(char[] a1, char[] a2)的思想:
* 首先:a1[0]对应的是第一个被加数的最高位,a2[0]同样,所以做加法的时候应该从a1[a1.length-1]位开始,或者将a1前后转置
* 然后加法的计算是:(a1[1]+a2[1]+进位)%10 进位=(a1[1]+a2[1]+进位)/10
* 然后就是字符与数字之前的转换,千万不要搞混
*/
public static char[] AddLongInteger(char[] a1, char[] a2){
int len=0;
if(a1.length > a2.length){
len = a1.length + 1;
}else{
len = a2.length + 1;
}
char[] temp = new char[len];
char[] result;
char[] b1 = new char[a1.length];
char[] b2 = new char[a2.length];
for(int i = 0;i < a1.length;i++){
b1[a1.length - 1 - i] = a1[i];
}
for(int i = 0;i < a2.length;i++){
b2[a2.length - 1 - i] = a2[i];
}
for(int i = 0; i < temp.length; i++){
temp[i] = '0';
}
for(int i = 0; i < len-1;i++){
int res = 0;
if(b1.length -1 - i >=0 && b2.length -1 - i >= 0){
res = b1[i] - '0' + b2[i] - '0';
}else if(b1.length -1 - i >= 0 && b2.length -1 - i < 0){
res = b1[i] - '0';
}else if(b1.length -1 - i < 0 && b2.length -1 - i >= 0){
res = b2[i] - '0';
}
int value = temp[i]-'0'+res;
temp[i] = (char) (value%10 + '0') ;
temp[i+1] += value/10;
// System.out.println(temp[i]);
// System.out.println(temp[i+1]);
}
while(temp[len - 1] == '0'){
len--;
}
result = new char[len];
int s = result.length;
for(int i = 0;i < s; i++){
result[s-1-i] = temp[i];
}
return result;
}
}