Java 后面判定是否为0结尾的两位数
发布网友
发布时间:2022-05-05 15:59
我来回答
共1个回答
热心网友
时间:2022-06-27 17:45
你前面的代码逻辑没动(变量名sum改为了sum1)
在你的代码后来添加了你要的判断逻辑,最终代码如下
import java.util.Scanner;
public class A2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
String[] digitals = String.valueOf(num).split("");
int sum1 = 0;
int sum2 = 0;
for (int i = 1; i <= digitals.length; i++) {
if (i % 2 != 0) {
sum1 += Integer.parseInt(digitals[i - 1]);
} else {
int n = Integer.parseInt(digitals[i - 1]) * 2;
sum2 += n / 10 + n % 10;
}
}
System.out.println("sum of odd numbers " + sum1);
System.out.println("sum of even numbers " + sum2);
// 判断是否合理
int sum = sum1 + sum2;
if (sum < 10) {
// 一位数,不合理
System.out.println("sum1 + sum2 = " + sum + ",需要加上" + (10 - sum));
} else if (sum > 99) {
// 三位数,不合理
System.out.println("sum1 + sum2 = " + sum + ",需要减去" + (sum - 90));
} else if (sum % 10 != 0) {
// 尾数不是0,不合理
int remainder = sum % 10;
if (sum > 90) {
System.out.println("sum1 + sum2 = " + sum + ",需要减去" + remainder);
} else {
System.out.println("sum1 + sum2 = " + sum + ",需要减去" + remainder + "或者加上" + (10 - remainder));
}
System.out.println();
} else {
System.out.println("sum1 + sum2 = " + sum + ",合理");
}
}
}