Eat Study Love

먹고 공부하고 사랑하라

Coding_Practice

Fraction Addition and Subtraction[M,Math,String,Simulation]

eatplaylove 2024. 8. 23. 11:30

https://leetcode.com/problems/fraction-addition-and-subtraction/description/?envType=daily-question&envId=2024-08-23

Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format.

The final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1. So in this case, 2 should be converted to 2/1.

 

Example 1:

Input: expression = "-1/2+1/2"
Output: "0/1"

Example 2:

Input: expression = "-1/2+1/2+1/3"
Output: "1/3"

Example 3:

Input: expression = "1/3-1/2"
Output: "-1/6"

 

Constraints:

  • The input string only contains '0' to '9', '/', '+' and '-'. So does the output.
  • Each fraction (input and output) has the format ±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted.
  • The input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range [1, 10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above.
  • The number of given fractions will be in the range [1, 10].
  • The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.

분수계산하는 코드를 짜는 것이다.

계산이야 어떻게든 할 거 같은데, Output 까지도 분수형태로 나타내라는 것이 좀 짜친다.

 

쉽지 않은 수학 문제다.

재미없다.

 

1. C

int gcd(int a, int b) {
    return (b==0)?a:gcd(b,a%b);
}

char *fractionAddition(char *S) {
    char *R = S;
    int p=0, q=1;
    while(*S){
        bool neg = (*S=='-');
        if(*S=='-' || *S=='+') S++;
        int x=0, y=0;
        while(*S!='/')
            x = 10*x + *(S++)-'0';
        S++;
        while('0'<=*S && *S<='9')
            y = 10*y + *(S++)-'0';
        if(neg)
            x *= -1;
        p = p*y+x*q;
        q *= y;
        int g = gcd(p,q);
        p /= g;
        q /= g;
    }
    if(q<0) {
        p*=-1;
        q*=-1;
    }
    // printf("%i/%i",p,q);
    sprintf(R,"%i/%i",p,q);
    return R;
}

 

2. Python

from math import gcd

def lcm(a, b):
    return a * b // gcd(a, b)

def fractionAddition(expression: str) -> str:
    numer = 0  # 분자
    denom = 1  # 분모
    i = 0
    n = len(expression)
    
    while i < n:
        # 부호 처리
        sign = 1
        if expression[i] == '-' or expression[i] == '+':
            if expression[i] == '-':
                sign = -1
            i += 1
        
        # 분자 추출
        num = 0
        while i < n and expression[i].isdigit():
            num = num * 10 + int(expression[i])
            i += 1
        num *= sign
        
        # '/' 건너뛰기
        i += 1
        
        # 분모 추출
        den = 0
        while i < n and expression[i].isdigit():
            den = den * 10 + int(expression[i])
            i += 1
        
        # 공통 분모를 이용하여 분수 계산
        lcm_val = lcm(denom, den)
        numer = numer * (lcm_val // denom) + num * (lcm_val // den)
        denom = lcm_val
        
        # 최대 공약수로 분수를 간단화
        g = gcd(abs(numer), denom)
        numer //= g
        denom //= g
    
    return f"{numer}/{denom}"

# 테스트용 메인 함수
expression = "-1/2+1/2+1/3"
result = fractionAddition(expression)
print(f"Result: {result}")