File tree Expand file tree Collapse file tree 1 file changed +14
-10
lines changed
tdd_intro/homework/02_ternary_numbers Expand file tree Collapse file tree 1 file changed +14
-10
lines changed Original file line number Diff line number Diff line change @@ -17,23 +17,27 @@ The last place in a ternary number is the 1's place. The second to last is the 3
1717If your language provides a method in the standard library to perform the conversion, pretend it doesn't exist and implement it yourself.
1818*/
1919
20- std::string ConvertTernary (std::string ternaryNumber)
20+ std::string ConvertTernary (const std::string& ternaryNumber)
2121{
2222 if (ternaryNumber.empty ())
2323 {
24- return " " ;
24+ return std::string ( " " ) ;
2525 }
26- int ternaryInt = std::stoi (ternaryNumber);
2726
28- if (ternaryInt == 20201 )
27+ int result = 0 ;
28+ for (int i = ternaryNumber.size () - 1 , value = 1 ; i >= 0 ; --i)
2929 {
30- return " 181" ;
30+ int currentSymbol = static_cast <int >(ternaryNumber[i]) - 48 ; // ASCII. 48 - 0, 49 - 1 and so on
31+ if (!(currentSymbol >= 0 && currentSymbol <= 3 ))
32+ {
33+ return 0 ;
34+ }
35+
36+ result += currentSymbol * value;
37+ value *= 3 ;
3138 }
32- if (ternaryInt == 20 )
33- {
34- return " 6" ;
35- }
36- return " 1" ;
39+
40+ return std::to_string (result);
3741}
3842
3943TEST (TernaryConvertion, Convert1)
You can’t perform that action at this time.
0 commit comments