zoukankan      html  css  js  c++  java
  • 大数加法

           以前用C的char数组做的,今天用C++的string写了一遍。

    代码:

     1 #include <string>
    2 #include <iostream>
    3 using namespace std;
    4
    5 string add(string s1,string s2);
    6 int carry;
    7
    8 int main()
    9 {
    10 string a,b;
    11 int T,i,j,k=1;
    12 cin>>T;
    13 do
    14 {
    15 cin>>a>>b;
    16 cout<<"Case "<<k++<<":"<<endl;
    17 cout<<a<<" + "<<b<<" = "<<add(a,b)<<endl;
    18 }while(--T);
    19
    20 //system("pause");
    21 return 0;
    22 }
    23
    24 string add(string s1,string s2)
    25 {
    26 string s;
    27 string::size_type i,j;
    28 int t,carry,len1,len2;
    29
    30 if(s1.length() < s2.length())
    31 {
    32 s = s1;
    33 s1 = s2;
    34 s2 = s;
    35 }
    36 len1 = s1.length();
    37 len2 = s2.length();
    38
    39 carry = 0;
    40 for(i = len1-1 ,j = len2-1; j != string::npos ; --i,--j)
    41 {
    42 t =s1[i]-'0' + s2[j]-'0'+carry;
    43 s1[i] ='0' + t%10;
    44 carry = t/10;
    45 }
    46
    47 if(carry)
    48 for(j = i ; j != string::npos; --j)
    49 {
    50 t = s1[j]-'0'+carry;
    51 s1[j] = '0' +t%10;
    52 carry = t/10;
    53 }
    54 if(carry) s1.insert(0,1,'1');
    55 return s1;
    56 }



  • 相关阅读:
    EL表达式 与 servlvet3.0的新规范
    回调函数
    结构体
    指针函数 和 函数指针
    BCC校验(异或和校验)
    stm32 USART串口通信
    stm32 中断
    Systick系统滴答定时器
    stm32f7 时钟
    按键连按和不连按
  • 原文地址:https://www.cnblogs.com/HpuAcmer/p/2432051.html
Copyright © 2011-2022 走看看