您的位置:首页 > 其它

实现两个超长正整数相加

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()));
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: