Skip to Content
CoursesCSC122โปรแกรมบวกเลข 5 ตัวต่อไป

โปรแกรมบวกเลข 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:

  1. If the last digit is 3, subtract that number.
  2. If the fist digit is 2 or 5, subtract that number.
  3. If the middle digit is 4 (in case of there are odd digits), subtract that number.
  4. Otherwise, add the number.
InputOutput
20-115
79244
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; } }

คำอธิบาย

ปรับปรุงล่าสุด