Re: [閒聊] 每日leetcode

作者: oin1104 (是oin的說)   2024-08-23 12:48:25
題目:
給你字串
-1/2+1/2
3/6-1/3+2/5-10/2
要你算出結果
思路:
機掰
超麻煩
直接做一個class num
然後用operator處理加減
生成num就暴力的一個一個字放進去
姆咪
```cpp
class num{
public:
int up;
int down;
num(){
up = 0;
down = 1;
}
num operator+(const num &a){
num res;
res.up = up * a.down + a.up * down;
res.down = down * a.down;
for(int i = 2 ; i <= 100 ; i ++)
{
while( res.up%i == 0 && res.down%i == 0 )
{
res.up /= i;
res.down /= i;
}
}
return res;
}
};
class Solution {
public:
string fractionAddition(string exp)
{
int len = exp.size();
int i = 0 ;
num k ;
int kneg = 1;
if (exp[i] == '-'){
kneg = -1;
i++;
}
k.up = exp[i] - '0';
if (i + 1 < len && exp[i + 1] == '0') {
k.up = 10;
i++;
}
k.up *= kneg;
if (i + 3 < len && exp[i + 2] == '1' && exp[i + 3] == '0')
{
k.down = 10;
i += 4;
}
else
{
k.down = exp[i + 2] - '0';
i += 3;
}
while (i < len) {
num now;
int neg = 1;
if (exp[i] == '-')
{
neg = -1;
i++;
}
else if (exp[i] == '+')
{
i++;
}
now.up = exp[i] - '0';
if (i + 1 < len && exp[i + 1] == '0')
{
now.up = 10;
i++;
}
now.up *= neg;
if (i + 3 < len && exp[i + 2] == '1' && exp[i + 3] == '0')
{
now.down = 10;
i += 4;
}
else
{
now.down = exp[i + 2] - '0';
i += 3;
}
k = k + now;
}
string ress;
ress += to_string(k.up);
ress += "/";
ress += to_string(k.down);
return ress;
}
};```
作者: JIWP (JIWP)   2024-08-23 12:49:00
你有什麼用
作者: mrsonic (typeB)   2024-08-23 12:52:00
我好討厭你
作者: sustainer123 (caster)   2024-08-23 12:58:00
大師
作者: dont   2024-08-23 13:34:00
大師

Links booklink

Contact Us: admin [ a t ] ucptt.com