• 模板:大整数除法


     1 string sub(string s1,string s2)
     2 {
     3     int flag = 0;
     4     if(s1.length()<s2.length() || (s1.length()==s2.length() && s1 < s2))
     5     {
     6         flag = 1;
     7         string temp=s1;
     8         s1=s2;
     9         s2=temp;
    10     }
    11 
    12 
    13     int i,j;
    14     for(i=s1.length()-1,j=s2.length()-1;i>=0;i--,j--)
    15     {
    16         s1[i]=char(s1[i]-(j>=0?s2[j]-'0':0));   //注意细节
    17         if(s1[i]-'0'<0)
    18         {
    19             s1[i]=char(s1[i] + 10);
    20             s1[i-1]--;
    21         }
    22     }
    23 
    24     for(i = 0; i < s1.length(); i++)
    25     {
    26         if(s1[i] != '0') break;
    27     }
    28     if(i == s1.length()) i = s1.length()-1;
    29     s1 = s1.substr(i);
    30 
    31     if(flag) s1 = "-" + s1;
    32 
    33     return s1;
    34 }
    35 string sum(string s1,string s2)
    36 {
    37     if(s1.length()<s2.length())
    38     {
    39         string temp=s1;
    40         s1=s2;
    41         s2=temp;
    42     }
    43     int i,j;
    44     for(i=s1.length()-1,j=s2.length()-1;i>=0;i--,j--)
    45     {
    46         s1[i]=char(s1[i]+(j>=0?s2[j]-'0':0));   //注意细节
    47         if(s1[i]-'0'>=10)
    48         {
    49             s1[i]=char((s1[i]-'0')%10+'0');
    50             if(i) s1[i-1]++;
    51             else s1='1'+s1;
    52         }
    53     }
    54     return s1;
    55 }
    56 
    57 string div(string s1,string s2)
    58 {
    59     string res = "0";
    60     if(s1.length()<s2.length() || (s1.length()==s2.length() && s1 < s2))
    61     {
    62         return "0";
    63     }
    64 
    65     int i;
    66     int sub_length = s1.length() - s2.length();
    67     for(i = sub_length; i >= 0; i--)
    68     {
    69         string s3(i,'0');
    70         string s4 = s2 + s3;
    71         
    72         do
    73         {
    74             string temp = sub(s1,s4);
    75             if(temp[0] == '-') break;
    76             else
    77             {
    78                 s1 = temp;
    79                 res = sum(res,("1" + s3));
    80             }
    81         }while(1);
    82     }
    83     return res;
    84 }
  • 相关阅读:
    flutter填坑之旅(widget原理篇)
    二次封装Element UI Table实现动态列
    vue使用import()提示语法错误
    flutter填坑之旅(配置本地资源文件)
    vue项目提示TypeError: e.call is not a function
    fork树
    从标准输入读取一行数组并保存(用的是字符串分割函数strtok_s() )
    常用算法链接:
    排序算法
    牛客网未通过代码---
  • 原文地址:https://www.cnblogs.com/mobileliker/p/3516939.html
Copyright © 2020-2023  润新知