罗小白


私信TA

用户名:Timmmmy

访问量:16382

签 名:

隔一年又回来刷题了...

等  级
排  名 141
经  验 7192
参赛次数 0
文章发表 46
年  龄 0
在职情况 学生
学  校
专  业

  自我简介:

有问题可以互相交流,共同提高 欢迎私信,请多指教:)

解题思路:
        正数的补码即其原码,负数的补码,除符号位取反加一(reverse、add1)
注意事项:
        
参考代码:

#include<bits/stdc++.h>
using namespace std;

void reverse(string& s)
{
    for (int i = 1; i < 16; ++i) {
        if (s[i] == '0') s[i] = '1';
        else s[i] = '0';
    }
}

void add1(string& s) {
    bool carryBit = false;
    if (s[15] == '0') {
        s[15] = '1';
    }
    else {
        s[15] = '0';
        carryBit = true;
        for (int i = 14; i >= 0; --i) {
            if (s[i] == '0' && carryBit) {
                s[i] = '1';
                carryBit = false;
                break;
            }
            if (s[i] == '1' && carryBit) {
                s[i] = '0';
            }
        }
    }
}

int main()
{
    string s;
    cin >> s;

    if (s[0] != '0') {
        reverse(s);
        add1(s);
    }
    cout << s << endl;

    return 0;
}


 

0.0分

5 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答

代码解释器

  评论区