โปรแกรมบวกเลข 5 ตัวต่อไป
โจทย์
Write a program to find sum of numbers by adding or subtracting the next five integer numbers from the given number (not included in the sum) according to the following conditions:
- If the last digit is 3, subtract that number.
- If the fist digit is 2 or 5, subtract that number.
- If the middle digit is 4 (in case of there are odd digits), subtract that number.
- Otherwise, add the number.
| Input | Output |
|---|---|
| 20 | -115 |
| 79 | 244 |
| 345 | -1040 |
โค้ด
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
int sum = 0;
for (int i = 0; i < 5; i++) {
int currentNum = num + i + 1;
int multiplier = determineMultiplier(currentNum);
sum += multiplier * currentNum;
}
System.out.print(sum);
}
private static int determineMultiplier(int number) {
String numStr = String.valueOf(number);
int length = numStr.length();
boolean endsWithThree = numStr.endsWith("3");
boolean startsWithTwoOrFive = numStr.startsWith("2") || numStr.startsWith("5");
boolean middleIsFour = length > 2 && length % 2 == 1 && numStr.charAt(length / 2) == '4';
return (endsWithThree || startsWithTwoOrFive || middleIsFour) ? -1 : 1;
}
}คำอธิบาย
ปรับปรุงล่าสุด