Editorial for Victor's Various Adventures - Victor Climbs Mt. Everest


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.

Submitting an official solution before solving the problem yourself is a bannable offence.

Prerequisites: Loops, Input/Output, Arithmetic Operations

Observation

The way to solve this problem is very simple. Since the operators given is only + or -, we do not have to consider the order of operations.

Solution

For the sample case:

5 + 11 - 4 + 234.5 - 3 + 22.123

Using Scanner, we can read the initial value 5.

After that, we can read the individual operators, and the values that is associated with them.

Operations:

  • + 11
  • - 4
  • + 234.5
  • - 3
  • + 22.123

After we have calculated the final result, we can format the output using DecimalFormat

import java.text.DecimalFormat;
import java.util.Scanner;

/**
 * @author Encodeous
 * Solution to https://tssoj.ca/problem/victor1
 */
public class Victor1 {
    public static void main(String[] args) {
        // Read Input
        Scanner sc = new Scanner(System.in);
        // Read the initial value
        double initialValue = sc.nextDouble();
        // Apply operators until the '=' sign
        while (true) {
            String operator = sc.next();
            // check if it is the '=' sign
            if (operator.equals("="))
                break;
            // read and parse the number
            String value = sc.next();
            double doubleValue = Double.parseDouble(value);
            // apply the operation
            if (operator.equals("+")) {
                initialValue += doubleValue;
            } else {
                initialValue -= doubleValue;
            }
        }
        // format the output
        DecimalFormat df = new DecimalFormat("0.0");
        System.out.println(df.format(initialValue));
    }
}

Comments

There are no comments at the moment.