HDU A + B Problem II

原题链接:

思路:用数组模拟手算,代码有点问题一直没AC,还以为有负数测试点,其实是进位标志没有更新,进位标志每次都要更新为0。还要注意前导零

#include<bits/stdc++.h>
using namespace std;
const int maxn=1005;
int T;
string str1,str2;
char str[maxn];
void add(const string &s1,const string &s2){
    int m1=s1.size(),m2=s2.size();
    int m=max(m1,m2);
    int sz=m;
    //flag进位标志
    int flag=0,x=0;
    str[m]='\0';
    while(m1>0&&m2>0){
        x=s1[--m1]+s2[--m2]+flag-96;
        flag=0;
        if(x>=10){
            flag=1;
        }
        str[--m]=x%10+48;
    }
    while(m1>0){
        x=s1[--m1]+flag-48;
        flag=0;
        if(x>=10){
            flag=1;
        }
        str[--m]=x%10+48;
    }
    while(m2>0){
        x=s2[--m2]+flag-48;
        flag=0;
        if(x>=10){
            flag=1;
        }
        str[--m]=x%10+48;
    }
    if(flag){
        putchar('1');
    }
    while(m<sz-1&&str[m]=='0'){
        m++;
    }
    printf("%s",str+m);
}
//写了个减法的,并没有用上
void sub(const string &s1,const string &s2){
    int m1=s1.size(),m2=s2.size();
    int flag=0,x=0,m=m1;
    int sz=m;
    str[m]='\0';
    while(m2>0){
        x=s1[--m1]-s2[--m2]-flag;
        flag=0;
        if(x<0){
            x+=10;
            flag=1;
        }
        str[--m]=x+48;
    }
    while(m1>0){
        x=s1[--m1]-flag-48;
        flag=0;
        if(x<0){
            x+=10;
            flag=1;
        }
        str[--m]=x+48;
    }
    while(m<sz-1&&str[m]=='0'){
        m++;
    }
    printf("%s",str+m);
}
bool cmp(const string &s1,const string &s2){
    if(s1.size()!=s2.size()){
        return s1.size()>s2.size();
    }
    return s1>s2;
}
void solve(){
    cin>>str1>>str2;
    cout<<str1<<" + "<<str2<<" = ";
    int m1=str1.size(),m2=str2.size();
    if(str1[0]=='-'&&str2[0]=='-'){
        putchar('-');
        add(str1.substr(1,m1-1),str2.substr(1,m2-1));
    }else if(str1[0]!='-'&&str2[0]!='-'){
        add(str1,str2);
    }else{
        if(str1[0]=='-'){
            string substr1=str1.substr(1,m1-1);
            if(cmp(substr1,str2)){
                putchar('-');
                sub(substr1,str2);
            }else{
                sub(str2,substr1);
            }
        }else{
            string substr2=str2.substr(1,m2-1);
            if(cmp(substr2,str1)){
                putchar('-');
                sub(substr2,str1);
            }else{
                sub(str1,substr2);
            }
        }
    }
}
int main(){
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    cin>>T;
    for(int i=0;i<T;i++){
        printf("Case %d:\n",i+1);
        solve();
        cout<<endl;
        if(i!=T-1){
            cout<<endl;
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值