题解 | #奇偶校验#

奇偶校验

https://www.nowcoder.com/practice/729d11d043d8448e83befa1410b694fe

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



int main() {
    string s;
    while(cin>>s){
        int a[8]={0};
        for(int i=0;i<s.size();i++){
            int n = s[i];// ascii
            for(int j=0;j<8;j++){
                // 转二进制
                if(n%2 == 0) a[7-j] = 0;
                else a[7-j] = 1;
                n /= 2;
            }

            int cnt=0;
            // 二进制中 1 的个数
            for(int k=0;k<8;k++){
                if(a[k] == 1) cnt++;
            }
            // 偶数个1,需要把最高位置为1,这样8位里面1的个数就是奇数了
            if(cnt % 2 == 0) a[0]=1;
            for(int k=0;k<8;k++) cout<<a[k];
            cout<<endl;
            
        }
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

二十岁的编程男神王大...:读博吧兄弟,你这绩点太好了,何必转码,另外哈哈哈真见到有括号标出来985的,这个不标注也知道吧
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务