The Elegance of Addition
Addition is straightforward, isn't it? When we encounter a number in our expression string, we simply add it to our running total, which we'll call result
. That's about it for addition.
Subtraction as "Negative Addition"
Here's where the subtlety comes in. Instead of thinking of subtraction as a separate operation, let's reframe it as adding a negative number. This concept simplifies our logic beautifully. Now, we don't have to juggle between two different operations; it's all addition!
A Practical Example: '1-1'
To illustrate how this works, let's consider the expression 1-1
. Our logic could flow as follows:
- Initialize
result
to 0. - Loop through each character in the string '1-1'.
- Identify what each character is:
- If it's a number, add it to
result
. - If it's a
-
sign, prepare to make the next number negative.
By following these steps, we'll add 1 to result
, and then effectively add -1 to result
, resulting in a final value of 0.