2021牛客暑期多校训练营7 I xay loves or 二进制运算

2021牛客暑期多校训练营7

I xay loves or 二进制运算

【题目描述】
xay loves or. He gives you x and s, you need to calculate how many positive integer y satisfy x or y=s .

【输入描述】
The first line contains two positive integers x and s .

It’s guaranteed that 1≤x,s<2^31 .

【输出描述】
Print the number of y satisfy x or y=s .

【样例】
输入

2 5

输出

0

【解题思路】

输入两个正数x和s,求使得 按位或运算x|y=s 的y的个数。

可以将x和s转换为二进制。如果x长度比s大,则必然不可能存在y,输出0;否则逐位考虑y该位上的可能性,更新答案值。

注意细节,要求的是满足条件的正数的个数,因此当y=0满足时(也即x=s时),答案要减去1

【题解代码】

#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
int main()
{
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	long long x,s;
	string xx,ss;
	cin>>x>>s;
	while(x!=0)
	{
		if(x%2==1)
			xx+='1';
		else
			xx+='0';
		x/=2;
	}
	while(s!=0)
	{
		if(s%2==1)
			ss+='1';
		else
			ss+='0';
		s/=2;
	}
	//将x和s转换为二进制(低位在左高位在右)
	//cout<<xx<<endl<<ss<<endl;
	int len1=xx.length(),len2=ss.length();
	if(len1>len2)
	{
		cout<<0<<endl;
		return 0;
	}
	long long ans=1;
	int flag=1;
	for(int i=0;i<len1;i++)
	{
		if(xx[i]=='1'&&ss[i]=='0')
		{
			cout<<0<<endl;
			return 0;
		}
		if(xx[i]=='1'&&ss[i]=='1')
			ans*=2;
		if(xx[i]=='0'&&ss[i]=='1')
			flag=0;
	}
	if(len1<len2)
		flag=0;
	if(flag==1)
		cout<<ans-1<<endl;
	else
		cout<<ans<<endl;
	return 0;
}

队友代码

#include <bits/stdc++.h>
const int N = 2e5 + 100;
const int mod = 1e9 + 7;
using namespace std;
long long x, s;
signed main()
{
    cin.tie(nullptr)->sync_with_stdio(false);
    int _ = 1;
    // cin >> _;
    while (_--)
    {
        cin >> x >> s;
        long long ans = 1;
        int i;
        for (i = 31; i >= 0; i--)
        {
            int x1 = (1 << i) & x;
            int s1 = (1 << i) & s;
            if (x1 && s1 == 0)
            {
                ans = 0;
                break;
            }
            else if (x1 && s1)
                ans *= 2ll;
        }
        if (x == s)
            ans--;
        cout << ans << endl;
    }
    return 0;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

球王武磊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值