C#版 大數計算機–減法

來源:互聯網
上載者:User

class BigReduce : BigCalculate
 

   {
       
public override string Oper(string num1, string num2)
       
{
           
bool isMinus = false;
           
//先判斷計算結果是否為正數(即num1是否大於num2),如果相等,直接返回0
           
//若結果為負數,則互換num1,num2,並在傳回值前加'-'
           
if (num1.Equals(num2))
           
{
               
return "0";
           
}
           
else if (Max(num1, num2).Equals(num2))//如果預計計算結果為負數,則將num1
num2調換
           
{
               
ChangeNum(ref num1, ref num2);
               
isMinus = true;
           
}

           
#region MyRegion
           
//獲得較大數的位元
           
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--)
           
{
               
if (tempNum1[i] >= tempNum2[i] + flag)
               
{
                   
liCh.Add((char)(tempNum1[i] - tempNum2[i] - flag + '0'));
                   
flag = 0;
               
}
               
else
               
{
                   
liCh.Add((char)(tempNum1[i] - tempNum2[i] - flag + 10 +
'0'));
                   
flag = 1;
               
}
           
}

           
//若結果高位有0,則去掉
           
//若結果為負數,則返回結果加"-"
           
if (isMinus == true)
           
{
               
return "-" + InvertOrder(new
string(liCh.ToArray())).TrimStart('0');
           
}
           
return InvertOrder(new
string(liCh.ToArray())).TrimStart('0');
           
#endregion

       
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.