public class BigInt
{
const string PLUS_SYMBOL = "+";
const string MINUS_SYMBOL = "-";
public static string Add(string intA, string intB) {
bool flag;
intA = System.Text.RegularExpressions.Regex.Replace(System.Text.RegularExpressions.Regex.Replace(intA, "^[^0-9]*[+]?0*", "+"), "^.[^0-9][-]?0*", "-");
intB = System.Text.RegularExpressions.Regex.Replace(System.Text.RegularExpressions.Regex.Replace(intB, "^[^0-9]*[+]?0*", "+"), "^.[^0-9][-]?0*", "-");
bool isAdd = true;
if (!intA.StartsWith(MINUS_SYMBOL) && !intB.StartsWith(MINUS_SYMBOL))
{
flag = true;
}
else {
if (intA.StartsWith(MINUS_SYMBOL) && intB.StartsWith(MINUS_SYMBOL))
{
flag = false;
}
else if (intA.StartsWith(MINUS_SYMBOL))
{
if (intA.TrimStart('-').Equals(intB.TrimStart('+')))
{
return "0";
}
else {
flag = intA.TrimStart('-').CompareTo(intB.TrimStart('+')) >0? false : true;
}
isAdd = false;
}
else {
if (intA.TrimStart('+').Equals(intB.TrimStart('-')))
{
return "0";
}
else
{
flag = intA.TrimStart('+').CompareTo(intB.TrimStart('-'))>0 ? true : false;
}
isAdd = false;
}
}
char[] charA = intA.TrimStart('+').TrimStart('-').ToCharArray();
char[] charB = intB.TrimStart('+').TrimStart('-').ToCharArray();
if (isAdd)
{
return string.Format("{0}{1}", !flag ? "-" : string.Empty, AddChar(charA, charB));
}
else {
return string.Format("{0}{1}", !flag ? "-" : string.Empty, minusChar(charA, charB));
}
}
static string AddChar(char[] charA, char[] charB) {
int bitResult=0;
char[] charR = new char[Math.Max(charA.Length , charB.Length) + 1];
int len = 0;
if (charA.Length >= charB.Length)
{
while (len <= charB.Length-1)
{
bitResult = Convert.ToInt32(charA[charA.Length - 1 - len].ToString()) + Convert.ToInt32(charB[charB.Length - 1 - len].ToString()) + bitResult;
charR[charR.Length - 1 - len] = (Char)(bitResult % 10 + 48);
bitResult = bitResult / 10;
len++;
}
while (len <= charA.Length - 1)
{
bitResult = Convert.ToInt32(charA[charA.Length - 1 - len].ToString()) + bitResult;
charR[charR.Length - 1 - len] = (Char)(bitResult % 10 + 48);
bitResult = bitResult / 10;
len++;
}
}
else {
while (len <= charA.Length-1)
{
bitResult = Convert.ToInt32(charB[charB.Length - 1 - len].ToString()) + Convert.ToInt32(charA[charA.Length - 1 - len].ToString()) + bitResult;
charR[charR.Length - 1 - len] = (Char)(bitResult % 10 + 48);
bitResult = bitResult / 10;
len++;
}
while (len <= charB.Length - 1)
{
bitResult = Convert.ToInt32(charB[charB.Length - 1 - len].ToString()) + bitResult;
charR[charR.Length - 1 - len] = (Char)(bitResult % 10 + 48);
bitResult = bitResult / 10;
len++;
}
}
charR[0] = (Char)(bitResult + 48); ;
return System.Text.RegularExpressions.Regex.Replace(System.Text.RegularExpressions.Regex.Replace(new string(charR), "^[+]?0*", string.Empty), "^[-]0*", "-");
}
static string minusChar(char[] minuend, char[] subtrahend) {
return string.Empty;
}
}
大整数加法初稿--未完成
最新推荐文章于 2021-07-11 20:14:53 发布