实现两个超长正整数相加
2017-06-03 19:46
232 查看
实现两个超长正整数相加
public class AddString {
public String AddLongInteger(String addend, String augend) {
/**
* 保证addend始终为较长的字符串
*/
if(addend.length() < augend.length()) {
String t = addend;
addend = augend;
augend = t;
}
int n1 = addend.length();
int n2 = augend.length();
/**
* 长度对齐
*/
StringBuffer t = new StringBuffer();
for(int i = 0;i < n1-n2;i++) {
t.append(0);
}
augend = t.append(augend).toString();
/**
* 相加结果保存在ch字符数组中
*/
char[] ch = new char[n1+1];
for(int i = 0;i < n1+1;i++) {
ch[i] = '0';
}
for(int i = n1;i > 0;i--) {
/**
* 取出相加的数
*/
int a = addend.charAt(i-1)-'0';
int b = augend.charAt(i-1)-'0';
//转为字符
int c = ch[i]-'0'+a+b;
//ch[i]本位和 ch[i-1]进位
ch[i] = (char)(c%10+'0');
ch[i-1] = (char)(c/10+'0');
}
String str = "";
if(ch[0] == '0') {
str = new String(ch,1,ch.length-1);
} else {
str = new String(ch);
}
System.out.println(str.length());
return str;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
System.out.println(new AddString().AddLongInteger(sc.next(), sc.next()));
}
}
}
public class AddString {
public String AddLongInteger(String addend, String augend) {
/**
* 保证addend始终为较长的字符串
*/
if(addend.length() < augend.length()) {
String t = addend;
addend = augend;
augend = t;
}
int n1 = addend.length();
int n2 = augend.length();
/**
* 长度对齐
*/
StringBuffer t = new StringBuffer();
for(int i = 0;i < n1-n2;i++) {
t.append(0);
}
augend = t.append(augend).toString();
/**
* 相加结果保存在ch字符数组中
*/
char[] ch = new char[n1+1];
for(int i = 0;i < n1+1;i++) {
ch[i] = '0';
}
for(int i = n1;i > 0;i--) {
/**
* 取出相加的数
*/
int a = addend.charAt(i-1)-'0';
int b = augend.charAt(i-1)-'0';
//转为字符
int c = ch[i]-'0'+a+b;
//ch[i]本位和 ch[i-1]进位
ch[i] = (char)(c%10+'0');
ch[i-1] = (char)(c/10+'0');
}
String str = "";
if(ch[0] == '0') {
str = new String(ch,1,ch.length-1);
} else {
str = new String(ch);
}
System.out.println(str.length());
return str;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
System.out.println(new AddString().AddLongInteger(sc.next(), sc.next()));
}
}
}
相关文章推荐
- 链表实现两个大正整数相加
- 超长正整数(超出long表数范围)的相加算法(Java实现)
- js中,实现两个数字相加
- 两个好大的数相加,不能用BigInteger来实现
- (链表实现)写出两个一元多项式相加的算法
- 两个巨大正整数相加
- 编程实现任意长度的两个正整数相加 代码实现
- 用汇编实现任意长度的两个整数相加
- 编程实现两个正整数的除法,当然不能用除法操作符
- 微软面试题:编程实现两个正整数的除法,不能用除法操作符
- (链表实现)写出两个一元多项式相加的算法
- 编程实现两个正整数的除法
- js中,实现两个数字相加
- 编程实现两个正整数的除法,当然不能用除法操作符
- 欧几里德算法实现求两个正整数的最大公因子
- 编程实现两个正整数的除法,当然不能用除法操作符
- js中,实现两个数字相加
- 用单链表实现两个大型整数的相加
- java中用ArrayList类实现正整数大数相加与相乘
- C++实现的一个简单两个大数相加程序!