题目描述
请设计一个算法完成两个超长正整数的加法。
接口说明
/*
请设计一个算法完成两个超长正整数的加法。
输入参数:
String addend:加数
String augend:被加数
返回值:加法结果
*/
public String AddLongInteger(String addend, String augend)
{
/*在这里实现功能*/
return null;
}
输入描述:
输入两个字符串数字
输出描述:
输出相加后的结果,string型
输入例子:
99999999999999999999999999999999999999999999999999
1
输出例子:
100000000000000000000000000000000000000000000000000
Java程序实现
- import java.util.Scanner;
- /**
- * 超长正整数相加
- *
- * @author LiJian
- *
- */
- public class Main {
- @SuppressWarnings("resource")
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Scanner sc = new Scanner(System.in);
- String str1 = "";
- String str2 = "";
- while (sc.hasNextLine()) {
- str1 = sc.nextLine();
- str2 = sc.nextLine();
- String sResult = AddLongInteger(str1, str2);
- System.out.println(sResult);
- }
- }
- public static String AddLongInteger(String str1, String str2) {
- if (str1.length() < str2.length()) {
- String temp = str1;
- str1 = str2;
- str2 = temp;
- }
- char[] charArr1 = str1.toCharArray();
- char[] charArr2 = str2.toCharArray();
- int jinWei = 0;
- int sum = 0;
- for (int i = charArr1.length - 1, j = charArr2.length - 1; i >= 0; i--) {
- if (j >= 0) {
- sum = Integer.parseInt(charArr1[i] + "") + Integer.parseInt(charArr2[j] + "") + jinWei;
- charArr1[i] = String.valueOf(sum % 10).charAt(0);
- jinWei = sum / 10;
- j--;
- } else {
- sum = Integer.parseInt(charArr1[i] + "") + jinWei;
- charArr1[i] = String.valueOf(sum % 10).charAt(0);
- jinWei = sum / 10;
- }
- }
- String value = "";
- for (int i = 0; i < charArr1.length; i++) {
- value += charArr1[i];
- }
- if (jinWei != 0) {
- return String.valueOf(jinWei) + value;
- } else {
- return value;
- }
- }
- }