C++位运算2AC8WA

P1001 A+B Problem

nUII @ 2024-08-11 10:52:25

#include <bits/stdc++.h>
using namespace std;
bool ac[29],bc[29];
int main()
{
    long long a,b;
    cin>>a>>b;
    stack<bool> at,bt;
    while(a)
    {
        at.push(a%2);
        a/=2;
    }
    int i=0;
    while(!(at.empty()))
    {
        bool o=at.top();
        ac[i]=o;
        i++;
        at.pop();
    }
    while(b)
    {
        bt.push(b%2);
        b/=2;
    }
    i=0;
    while(!(bt.empty()))
    {
        bool p=bt.top();
        bc[i]=p;
        i++;
        bt.pop();
    }
    if(a<0)
    {
        ac[28]=1;
    }
    if(b<0)
    {
        bc[28]=1;
    }
    bool c=0;
    for(int i=0;i<29;i++)
    {
        if(i==28)
        {
            bc[i]|=ac[i];
        }
        else
        {
            if(ac[i]&&bc[i])
            {
                if(c)
                {
                    c=1;
                }
                else
                {
                    c=1;
                    ~bc[i];
                }
            }
            else
            {
                if(ac[i]^bc[i])
                {
                    if(c)
                    {
                        c=1;
                        bc[i]=0;
                    }
                    else
                    {
                        bc[i]=1;
                    }
                }
                else
                {
                    if(c)
                    {
                        bc[i]=1;
                        c=0;
                    }
                    else
                    {
                        bc[i]=0;
                    }
                }
            }
        }
    }
    int sum=0;
    for(int i=0;i<29;i++)
    {
        if(bc[i])
        {
            if(i==0)
            {
                sum+=1;
            }
            else
            {
                int y=2;
                for(int j=0;j<i-1;j++)
                {
                    y*=2;
                }
                sum+=y;
            }
        }
    }
    cout<<sum;
    return 0;
}

求错因


by YangBC @ 2024-08-11 10:55:10

这题直接用intA+B就AC了,搞什么高精度?


by nUII @ 2024-08-11 10:58:00

不是谁不是闲的来做A+B啊


by _lxc__ @ 2024-08-11 11:09:41

逆天思路


by nUII @ 2024-08-11 11:32:59

挺好,逻辑没问题,但3+4=5


by hushuoyan @ 2024-08-18 14:33:16

a=input()
b=input()
a=int(a)
b=int(b)
print(a+b)

nice...(高精度也可用)


by nUII @ 2024-11-20 15:55:06

3+4=5


|