L1-025 正整数 A+B
题的目标很简单,就是求两个正整数A
和B
的和,其中A
和B
都在区间[1,1000]。稍微有点麻烦的是,输入并不保证是两个正整数。
输入格式:
输入在一行给出A
和B
,其间以空格分开。问题是A
和B
不一定是满足要求的正整数,有时候可能是超出范围的数字、负数、带小数点的实数、甚至是一堆乱码。
注意:我们把输入中出现的第 1 个空格认为是A
和B
的分隔。题目保证至少存在一个空格,并且B
不是一个空字符串。
输出格式:
如果输入的确是两个正整数,则按格式A + B = 和
输出。如果某个输入不合要求,则在相应位置输出?
,显然此时和也是?
。
输入样例 1:
tex
123 456
123 456
输出样例 1:
tex
123 + 456 = 579
123 + 456 = 579
输入样例 2:
22. 18
22. 18
输出样例 2:
? + 18 = ?
? + 18 = ?
输入样例 3:
-100 blabla bla...33
-100 blabla bla...33
输出样例 3:
? + ? = ?
? + ? = ?
Solution:
java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s = in.readLine();
String[] input = new String[2];
int indexOfSpace = s.indexOf(" ");
input[0] = s.substring(0, indexOfSpace);
input[1] = s.substring(indexOfSpace + 1);
StringBuilder sb = new StringBuilder();
boolean check = false;
int a = 0, b = 0;
if (input[0].matches("\\d+")) {
a = Integer.parseInt(input[0]);
if (a >= 1 && a <= 1000) {
sb.append(input[0]).append(" + ");
} else {
sb.append("? + ");
check = true;
}
} else {
sb.append("? + ");
check = true;
}
if (input[1].matches("\\d+")) {
b = Integer.parseInt(input[1]);
if (b >= 1 && b <= 1000) {
sb.append(input[1]).append(" = ");
} else {
sb.append("? = ");
check = true;
}
} else {
sb.append("? = ");
check = true;
}
if (check) {
sb.append("?");
} else {
sb.append(a + b);
}
System.out.println(sb);
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s = in.readLine();
String[] input = new String[2];
int indexOfSpace = s.indexOf(" ");
input[0] = s.substring(0, indexOfSpace);
input[1] = s.substring(indexOfSpace + 1);
StringBuilder sb = new StringBuilder();
boolean check = false;
int a = 0, b = 0;
if (input[0].matches("\\d+")) {
a = Integer.parseInt(input[0]);
if (a >= 1 && a <= 1000) {
sb.append(input[0]).append(" + ");
} else {
sb.append("? + ");
check = true;
}
} else {
sb.append("? + ");
check = true;
}
if (input[1].matches("\\d+")) {
b = Integer.parseInt(input[1]);
if (b >= 1 && b <= 1000) {
sb.append(input[1]).append(" = ");
} else {
sb.append("? = ");
check = true;
}
} else {
sb.append("? = ");
check = true;
}
if (check) {
sb.append("?");
} else {
sb.append(a + b);
}
System.out.println(sb);
}
}