题目描述
请设计一个算法完成两个超长正整数的加法。
输入描述:
输入两个字符串数字
输出描述:
请设计一个算法完成两个超长正整数的加法。
输入描述:
输入两个字符串数字
输出描述:
输出相加后的结果,string型
思路一:
import java.math.BigInteger;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
BigInteger n1 = scanner.nextBigInteger();
BigInteger n2 = scanner.nextBigInteger();
System.out.println(n1.add(n2));
}
}
}
思路二:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
String num1 = scanner.next();
String num2 = scanner.next();
StringBuffer sb = new StringBuffer();
while (num1.length() < num2.length())
num1 = "0" + num1;
while (num1.length() > num2.length())
num2 = "0" + num2;
int carry = 0;
int tmp = 0;
for (int i = num1.length() - 1; i >= 0; i--)
{
tmp = num1.charAt(i) - '0' + num2.charAt(i) - '0' + carry;
if (tmp >= 10)
{
carry = tmp / 10;
tmp = tmp % 10;
}
else
carry = 0;
sb.append(tmp);
}
if (carry > 0)
sb.append(carry);
System.out.println(sb.reverse().toString());
}
}
}
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
String num1 = scanner.next();
String num2 = scanner.next();
int resLen = Math.max(num1.length(), num2.length()) + 1;
char[] res = new char[resLen];
while (num1.length() < num2.length())
num1 = "0" + num1;
while (num1.length() > num2.length())
num2 = "0" + num2;
int carry = 0;
int tmp = 0;
int index = resLen;
String result = "";
for (int i = num1.length() - 1; i >= 0; i--)
{
tmp = num1.charAt(i) - '0' + num2.charAt(i) - '0' + carry;
if (tmp >= 10)
{
carry = tmp / 10;
tmp = tmp % 10;
}
else
carry = 0;
res[--index] = (char) (tmp + '0');
}
if (carry > 0)
{
res[--index] = (char) (carry + '0');
result = String.valueOf(res);
}
else
{
res[--index] = '0'; //必须赋值
result = String.valueOf(res).substring(1);
}
System.out.println(result);
}
}
}