标签:add error build temp 结果 vat 设计 [] system.in
请设计一个算法能够完成两个用字符串存储的整数进行相加操作,对非法的输入则返回error
输入为一行,包含两个字符串,字符串的长度在[1,100]。
输出为一行。合法情况输出相加结果,非法情况输出error
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;
}
}
标签:add error build temp 结果 vat 设计 [] system.in
原文地址:https://www.cnblogs.com/HwyStudy/p/9193212.html