哪位大佬帮我查一下错(违规紫衫)

P1001 A+B Problem

514czh @ 2024-06-28 13:29:25

二进制相加再转十进制

#include<bits/stdc++.h>
using namespace std;
long long a,b;
string n1,n2;
long long fanzhuan(string x1){
    long long q=1,ans=0;
    for(int i=0;i<x1.size();i++){
        ans+=int(x1[i]-'0')*q;
        q*=2;
    }
    return ans;
}
long long jia(string a1,string a2){
    string c="";
    long long w=min(a1.size(),a2.size()),m=max(a1.size(),a2.size());
    bool a12;
    if(w==a1.size())
    a12=0;
    else a12=1;
    for(int i=0;i<m;i++){
        if(i>=w)
        {
            if(a12){
                if(a1[i]=='1'&&c[i]=='1'){
                    c[i+1]='1';
                    c[i]='0';
                }
                else if(a1[i]=='0'&&c[i]=='1'){
                    c[i]='1';
                }else if(a1[i]=='0'&&c[i]=='0'){
                    c[i]='0';
                }else if(a1[i]=='1'&&c[i]=='0'){
                    c[i]='1';
                }
            }
            else {
                if(a2[i]=='1'&&c[i]=='1'){
                    c[i+1]='1';
                    c[i]='0';
                }
                else if(a2[i]=='0'&&c[i]=='1'){
                    c[i]='1';
                }else if(a2[i]=='0'&&c[i]=='0'){
                    c[i]='0';
                }else if(a2[i]=='1'&&c[i]=='0'){
                    c[i]='1';
                }
            }
        }
        else{
            int e=int(a1[i]-'0'+a2[i]-'0'+c[i]-'0');
            if(e==0)
            c[i]='0';
            if(e==1)
            c[i]='1';
            if(e==2)
            c[i]='0',c[i+1]='1';
            if(e==3)c[i]='1',c[i+1]='1';
        } 
    }
    return fanzhuan(c);
}
long long f(long long x,long long y){
    while(x){
        n1=char(x%2+'0')+n1;
        x/=2;
    }
    while(y){
        n2=char(y%2+'0')+n2;
        y/=2;
    }
    return jia(n1,n2);
}
signed main(){
    cin>>a>>b;
    cout<<f(a,b);
    return 0;
}

by Lyrith_with_xQ @ 2024-06-28 13:35:21

为什么不直接cout<<a+b呢


by cff_0102 @ 2024-06-28 13:42:46

@514czh 我虽然没认真看但是试一下111+111(二进制)之类的情况?


by zhengpie @ 2024-06-28 13:45:20

@Lyrith_with_xQ 重要的是写的要帅


by Infinity_Fantasy @ 2024-06-28 13:46:49

@514czh 是不是没处理负数


by Lyrith_with_xQ @ 2024-06-28 13:52:36

@zhengpie 简洁易懂才是王道


by 11Yang @ 2024-07-08 09:08:12

其实啊 直接cout<<a+b;就好了呢……


|