提交 0b7e3822 编写于 作者: 小代码2016's avatar 小代码2016

feat(calc_lib): 基本的大数加法(使用 make_unique 替代 new/delete), 只实现了整数

上级 86bb4a05
#include <iostream>
#include <memory>
#include <cstring>
#include <sstream>
#include <algorithm>
......@@ -8,36 +9,29 @@ KHL_CALC_NAMESPACE_BEGIN
std::string Decimal::add(std::string x, std::string y)
{
/** 入参转换为 int 数组, 并倒置 */
char * sx = const_cast<char *>(x.c_str());
char * sy = const_cast<char *>(y.c_str());
std::cout << "sx:" << sx << std::endl;
std::cout << "sy:" << sy << std::endl;
const size_t lx = strlen(sx);
const size_t ly = strlen(sy);
int * a = new int[lx];
int * b = new int[ly];
auto a = std::make_unique<int[]>(lx);
auto b = std::make_unique<int[]>(ly);
std::cout << "sx > a" << std::endl;
for (int i = 0; i < lx; i++)
{
a[lx - i] = sx[i] - '0';
std::cout << sx[i] << " " << a[lx - i] << std::endl;
}
std::cout << "sx > a" << std::endl;
std::cout << "sy > b" << std::endl;
for (int i = 0; i < ly; i++)
{
b[ly - i] = sy[i] - '0';
std::cout << sy[i] << " " << b[ly - i] << std::endl;
}
std::cout << "sy > b" << std::endl;
/** 计算 */
const size_t lc = std::max(lx, ly) + 1;
int * result = new int[lc];
auto result = std::make_unique<int[]>(lc);
for (int i = 0; i < lc; i++)
{
......@@ -46,30 +40,25 @@ std::string Decimal::add(std::string x, std::string y)
result[i] = result[i] % 10;
}
/** 删除前导0 */
size_t len = lc;
if (0 == result[lc] && lc > 0)
{
len--;
}
std::cout << "---" << std::endl;
char *c = new char[lc];
/** 翻转倒置的计算结果 */
auto c = std::make_unique<char[]>(lc);
for (int i = len, j = 0; i > 0; i--, j++)
{
std::cout << result[i] << std::endl;
c[j] = result[i] + '0';
}
std::cout << "---" << std::endl;
std::string str;
std::stringstream ss;
ss << c;
ss >> str;
delete[] a;
delete[] b;
delete[] result;
delete[] c;
return str;
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册