1. 程式人生 > >練習題13:整數加法

練習題13:整數加法

out void edr 相加 -s 操作 clas exce end

題目描述

請設計一個算法能夠完成兩個用字符串存儲的整數進行相加操作,對非法的輸入則返回error

輸入描述:

輸入為一行,包含兩個字符串,字符串的長度在[1,100]。

輸出描述:

輸出為一行。合法情況輸出相加結果,非法情況輸出error

Java解法:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class test04 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] str = br.readLine().split(" ");
String result = add(str[0], str[1]);
System.out.println(result);
}

private static String add(String s, String s1) {
char [] c1 = s.toCharArray();
char [] c2 = s1.toCharArray();
if (!check(c1) || !check(c2)) {
return "error";
}
if (c1.length < c2.length) {
char [] temp = c1;
c1 = c2;
c2 = temp;
}
int plus = 0;
int i = c1.length - 1, j = c2.length - 1;
while (j >= 0) {
int temp = c1[i] - ‘0‘ + c2[j] - ‘0‘ + plus;
plus = temp / 10;
c1[i] = (char)(temp % 10 + ‘0‘);
i--;
j--;
}
while (i >= 0 && plus > 0) {
int temp = c1[i] - ‘0‘ + plus;
plus = temp / 10;
c1[i] = (char)(temp % 10 + ‘0‘);
i--;
}
StringBuilder str = new StringBuilder();
if (plus > 0) {
str.append(‘1‘);
}
for (char c : c1) {
str.append(c);
}
return str.toString();
}

private static boolean check(char[] c) {
for (char aC : c) {
if (aC < ‘0‘ || aC > ‘9‘) {
return false;
}
}
return true;
}
}

練習題13:整數加法