文章

14

粉丝

39

获赞

0

访问

1.9k

头像
1097 负二进制
学习交流
发布于2024年2月27日 20:05
阅读数 199

大佬们这个代码能运行但结果错误,能不能看看哪里错了?

#include<bits/stdc++.h>
using namespace std;
int main(){
    int x;
    string s;
    while(scanf("%d",&x)!=EOF){
        while(x!=0){//循环停止条件
            int a=x%(-2);
            int yu,sh;
            if(a==0||a==1){//余数为0或1
                yu=a;
                sh=(x-a)/(-2);
            }
            else if(a==(-1)){//余数为-1
                yu=1;
                sh=(x-1)/(-2);
 ...

登录查看完整内容


登录后发布评论

2 条评论
snake VIP
2024年2月27日 21:43

#include<bits/stdc++.h>
using namespace std;
int main(){
    int x;
    while(scanf("%d",&x)!=EOF){
        string s;
        if (x == 0) s = "0";
        while(x!=0){//循环停止条件
            int a=x%(-2);
            int yu,sh;
            if(a==0||a==1){//余数为0或1
                yu=a;
                sh=(x-a)/(-2);
            }
            else if(a==(-1)){//余数为-1
                yu=1;
                sh=(x-1)/(-2);
            }
            s.push_back(yu+'0');
            x=sh;
        }
        for(int i=s.size()-1;i>=0;i--){
            cout<<s[i];
        }
        cout<<endl;
    }
}

 

赞(0)
snake VIP
2024年2月27日 21:39

string s;要放到while循环里,否则多组数据输入的时候会前面的结果会影响到后面的。

另外注意0要特判一下

赞(0)