-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
b2146d0
commit 81e71b6
Showing
1 changed file
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
#include <string> | ||
#include <vector> | ||
#include <sstream> | ||
#include <iostream> | ||
|
||
using namespace std; | ||
|
||
bool isLinear(string str) { | ||
for (char c : str) { | ||
if (c == 'x') { | ||
return true; | ||
} | ||
} | ||
|
||
return false; | ||
} | ||
|
||
int getNumber(string str) { | ||
int result = 0; | ||
|
||
for (char c : str) { | ||
if (isdigit(c)) { | ||
result = result * 10 + (c - '0'); | ||
} | ||
} | ||
|
||
return result; | ||
} | ||
|
||
string solution(string polynomial) { | ||
int linear = 0; | ||
int num = 0; | ||
string code; | ||
stringstream ss(polynomial); | ||
while (ss >> code) { | ||
if (code != "+") { | ||
if (isLinear(code)) { | ||
linear += getNumber(code); | ||
if (code.length() == 1) { | ||
linear++; | ||
} | ||
} else { | ||
num += getNumber(code); | ||
} | ||
} | ||
} | ||
|
||
string linearStr = ""; | ||
if (linear == 1) { | ||
linearStr = "x"; | ||
} else { | ||
linearStr = to_string(linear) + "x"; | ||
} | ||
|
||
if (linear != 0 && num != 0) { | ||
return linearStr + " + " + to_string(num); | ||
} else if (linear != 0) { | ||
return linearStr; | ||
} else { | ||
return to_string(num); | ||
} | ||
} |