LeetCode Daily: Fraction Addition and Subtraction Solution in Java | August 23, 2024

preview_player
Показать описание
🔍 LeetCode Problem of the Day: Fraction Addition and Subtraction

Today, we're solving the "Fraction Addition and Subtraction" problem in Java, as part of the LeetCode daily challenge series. This problem requires you to compute the result of adding and subtracting fractions represented as a string.

👉 Solution: Pinned on the comments

🌟 Problem Description:
In this challenge, you will add and subtract fractions represented in a string format. The goal is to return the result in its simplest form.

🔑 Code Explanation:
Parsing Fractions: The code first parses the input expression to extract individual fractions.
Calculation: It then calculates the sum by adjusting the numerators and denominators of the fractions.
Simplification: Finally, the greatest common divisor (GCD) is used to simplify the result.

📅 Daily Solutions:
I'm posting solutions to LeetCode daily problems every day. Stay tuned by subscribing and don't forget to hit the bell icon!

👥 Join the Community:
Discuss your solutions in the comments.
Engage with other coders and improve your problem-solving skills.
If this video helped you, please like, share, and subscribe for more daily LeetCode solutions!

#LeetCode #Coding #Programming #TechInterview #Math #DailyChallenge #Java
Рекомендации по теме
Комментарии
Автор

Code: class Solution {
public String fractionAddition(String expression) {
int numerator = 0;
int denominator = 1;

List<String> fractions = parseFractions(expression);

for(String frac : fractions) {
String[] parts = frac.split("/");
int num = Integer.parseInt(parts[0]);
int denom = Integer.parseInt(parts[1]);

numerator = numerator * denom + num * denominator;
denominator *= denom;

int gcd = gcd(Math.abs(numerator), Math.abs(denominator));
numerator /= gcd;
denominator /= gcd;
}
return numerator + "/" + denominator;

}

public int gcd(int a, int b) {
while(b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}

public List<String> parseFractions(String expression) {
List<String> fractions = new ArrayList<>();

int start = 0;
for(int i = 1; i < expression.length(); i++) {
if(expression.charAt(i) == '+' ||
expression.charAt(i) == '-') {
fractions.add(expression.substring(start, i));
start = i;
}
}

return fractions;
}
}

AlgoXploration