init: gtest and quiz 1.

This commit is contained in:
2025-05-19 21:09:08 +08:00
commit 992103fd7b
258 changed files with 113483 additions and 0 deletions

99
mixplus/src/parser.cpp Normal file
View File

@@ -0,0 +1,99 @@
#include "parser.h"
#include <sstream>
#include <stdexcept>
long mixplus::Parser::parseDigit(const std::string& input)
{
long result = 0;
for (const char& c : input)
{
if (c >= '0' && c <= '9')
{
result = result * 10 + (c - '0');
}
else
{
throw std::invalid_argument("The input string is invalid.");
}
}
return result;
}
long mixplus::Parser::parseHexadecimal(const std::string& input)
{
long result = 0;
for (const char& c : input)
{
if (c >= '0' && c <= '9')
{
result = result * 16 + (c - '0');
}
else if (c >= 'a' && c <= 'f')
{
result = result * 16 + (c - 'a' + 10);
}
else if (c >= 'A' && c <= 'F')
{
result = result * 16 + (c - 'A' + 10);
}
else
{
throw std::invalid_argument("The input string is invalid.");
}
}
return result;
}
long mixplus::Parser::parseNumber(const std::string& input)
{
if (input.size() > 2 && (input[1] == 'x' || input[1] == 'X'))
{
return parseHexadecimal(input.substr(2));
}
return parseDigit(input);
}
long mixplus::Parser::parseAndAdd(const int argc, const char** argv)
{
// 程序名称 first second
if (argc != 3)
{
throw std::invalid_argument("Less arguments is provided.");
}
const auto a = std::string(argv[1]);
const auto b = std::string(argv[2]);
const auto aValue = parseNumber(a);
const auto bValue = parseNumber(b);
return aValue + bValue;
}
Result mixplus::Parser::formatResult(const long value)
{
std::stringstream ss;
ss << std::hex;
ss << "0x";
// 处理负数:转换为无符号 long输出补码形式
if (value < 0)
{
ss << static_cast<unsigned long>(value);
}
else
{
ss << value;
}
return Result{
.hexadecimal = ss.str(), .digit = value
};
}