C#版 大數計算機–加法

來源:互聯網
上載者:User

///
 

   ///
基類,抽象類別,定義常用方法
    ///
    abstract
class BigCalculate
    {
       
public abstract string Oper(string num1, string num2);

       
//反轉數字順序
       
protected string InvertOrder(string str)
       
{
           
char[] chTemp = new char[str.Length];

           
for (int i = 0; i < str.Length; i++)
           
{
               
chTemp[i] = str[str.Length - i-1];
           
}

           
return new string(chTemp.ToArray());
       
}

       
//交換數字
       
protected void ChangeNum(ref string num1,ref string num2)
       
{
           
string strTemp = num1;
           
num1 = num2;
           
num2 = strTemp;
       
}
       
//獲得較大數
       
protected string Max(string num1, string num2)
       
{
           
if (num1.Length > num2.Length)
           
{
               
return num1;
           
}
           
else if (num1.Length==num2.Length)
           
{
               
for (int i = num1.Length-1; i >=0 ; i--)
               
{
                   
if (num1[i].CompareTo(num2[i])<0)
                   
{
                       
return num2;
                   
}
               
}
               
return num1;
           
}
           
return num2;
       
}
    }
--------------------------------------------------------------------------

    class
BigAdd:BigCalculate
    {
       
public override string Oper(string num1, string num2)
       
{
           
//獲得較大數的位元
           
int len = num1.Length > num2.Length ? num1.Length :
num2.Length;
           
//將較小數差位補0
           
string tempNum1 = new string('0', len - num1.Length) + num1;
           
string tempNum2 = new string('0', len - num2.Length) + num2;

           
int flag = 0;//進位符
           
List liCh = new List();//存放運算後數字
           
for (int i = len - 1; i >= 0; i--)
           
{
               
liCh.Add((char)(tempNum1[i] + tempNum2[i] + flag - '0'));
               
flag = (liCh[liCh.Count - 1] - '0') / 10;
               
liCh[liCh.Count - 1] = (char)(((liCh[liCh.Count - 1] - '0') % 10) +
'0');
           
}

           
//若運算完成後進位符不為0,及最高位進位,則再加一位
           
if (flag > 0)
           
{
               
liCh.Add((char)(flag + '0'));
           
}

           
return InvertOrder(new string(liCh.ToArray()));
       
}
    }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.