用字符串创建数字 [英] create numbers with strings

查看:100
本文介绍了用字符串创建数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个用字符串计算大数字的类。

Add方法不起作用。我认为逻辑是错误的。有任何建议如何解决这个问题?在此先感谢。



I am trying to create a class to calculate Big Numbers with strings.
The Add method isn't working. I think the logic is wrong. Any suggestions how to fix this? Thanks in advance.

#include "NumberString.h"


NumberString::NumberString()
{
	this->_number = "0";
}

NumberString::NumberString(string s)
{
	this->_number = s;
}

NumberString::~NumberString()
{
}

void NumberString::Add(string number)
{
	string top = this->_number;
	string bottom = number;
	if (number.size() > top.size())
	{
		top = number;
		bottom = _number;
	}
	string sum;
	char t=0, b=0, l=0, c='0';
	size_t n = top.size();
	size_t m = bottom.size();
	for (size_t i = 0; i < n; i++)
	{
		t = top.at(n - i - 1);
		if (c != '0')
		{
			this->AddChars(t, c, &l, &c);
		}

		if (i < m)
		{
			b = bottom.at(m - i - 1);
			this->AddChars(t, b, &l, &c);
		}

		sum.insert(0, 1, l);		
	}

	if (c != '0')
	{
		sum.insert(0, 1, c);
	}

	this->_number = sum;
}

void NumberString::AddChars(char first, char second, char *last, char* carry)
{
	*carry = '0';
	char c = first + second - '0';
	if (c > '9')
	{
		*carry = '1';
		c -= 10;
	}
	*last = c;
}

void NumberString::Multiply(uint64_t number)
{
	NumberString n = this->_number;
	if (number == 0)
	{
		this->_number = "0";
		return;
	}
	else if (number == 1)
		return;

	for (uint64_t i = 0; i < number-1; i++)
	{
		this->Add(n);
	}
}

void NumberString::Print()
{
	cout << this->_number.c_str() << endl;
}

string NumberString::GetNumber()
{
	return this->_number;
}

void NumberString::Add(NumberString number)
{
	this->Add(number._number);
}

推荐答案

您的代码未正确传播此处可能发生的进位

Your code doesn't properly propagate the carry that may occur here
Quote:

if(c!='0')

{

this- > AddChars(t,c,& l,& c);

}

if (c != '0')
{
this->AddChars(t, c, &l, &c);
}





此外,它不正确总是 t b 相加(当携带时,它应该与b相加)。



为了避免繁琐的进位传播,我建议定义



Moreover, it incorrectly always sums t with b (it should sum l with b when carry occurs).

In order to avoid cumbersome carry propagation, I would suggest to define

char NumberString::AddCharsWithCarry( char first, char second, char & carry)
{
  char r = first - '0' + second - '0' + carry;
  if ( r > '9')
  {
    r -= 10;
    carry = '1';
  }
  else
  {
    carry = '0';
  }
  return r;
}





此方法总和首先 second 携带,返回结果(并更新 carry 参数)。这样,添加方法中的循环就会变得非常简单:



This method sums first, second and carry, returning the result (and updating the carry parameter). This way the loop inside your Add method would become very simple:

for (size_t i = 0; i < n; i++)
{
  t = top.at(n - i - 1);
  b = i < m ? bottom.at(m -i -1) : '0';
  l = AddCharsWithCarry(t, b, c);

  sum.insert(0, 1, l);
}


这篇关于用字符串创建数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆