Basic Calculator || | Leetcode

แชร์
ฝัง
  • เผยแพร่เมื่อ 9 ก.พ. 2025
  • In this video, we break down a C++ program to evaluate basic arithmetic expressions involving addition, subtraction, multiplication, and division. Learn how the program:
    Time stamps:
    ✓ Problem Algorithm and Solution Approach (0:00)
    ✓ Live Coding (07:00)
    ✅ Parses expressions like "3+2*2"
    ✅ Uses a stack to handle operator precedence efficiently
    ✅ Processes the input in a single pass for optimal performance
    Time Complexity: O(N)
    Space Complexity: O(N)
    Perfect for coding interviews and competitive programming! Watch now to master this clean and effective solution. 💻✨
    🔗 Code Walkthrough and Dry Run:
    Example Input: "3-5/2"
    Step-by-Step Dry Run
    1. Initialization:
    s = "3-5/2+" (a + is appended to process the last number).
    num = 0, ans = 0, sign = '+', stack
    2. Processing Characters in the Loop:
    2.1. Character 3:
    It is a digit, so num = 0 * 10 + (3 - '0') = 3.
    2.2 Character -:
    sign is +, so st.push(3) (push current num to the stack).
    Reset num = 0, update sign = '-'.
    Stack: [3]
    2.3 Character 5:
    It is a digit, so num = 0 * 10 + (5 - '0') = 5.
    2.4 Character /:
    sign is -, so st.push(-5) (push -num to the stack).
    Reset num = 0, update sign = '/'.
    Stack: [3, -5]
    2.5 Character 2:
    It is a digit, so num = 0 * 10 + (2 - '0') = 2.
    2.6 Character +:
    sign is /, so:
    Pop the top of the stack: temp = -5.
    Compute temp / num = -5 / 2 = -2 (integer division truncates toward 0).
    Push the result back to the stack: st.push(-2).
    Reset num = 0, update sign = '+'.
    Stack: [3, -2]
    Final Accumulation:
    While the stack is not empty:
    Pop 3, add to ans: ans = 0 + 3 = 3.
    Pop -2, add to ans: ans = 3 + (-2) = 1.
    Result:
    The final result is 1.
    If you want to join in future sessions, get on our discord: / discord
    Follow us on official pages:
    Instagram: / tech.tourist
    Threads: www.threads.ne...
    My Course Lists:
    🚀Course On Redis: www.educative....
    🚀Course On SystemDesign: www.educative....
    🚀Course On Multithreading: www.educative....
    🚀Course On Apache Kafka: www.educative....
    🚀Course on Advance System Design www.educative....
    Like 👍 and Subscribe 🔔 for more coding tutorials! 🚀
    📌 Tags: #CPlusPlus #DataStructures #Algorithms #CodingInterview #techtourist #codingtutorial #codingjourney

ความคิดเห็น •